博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【spring Boot】spring boot1.5以上版本@ConfigurationProperties取消location注解后的替代方案...
阅读量:7060 次
发布时间:2019-06-28

本文共 2051 字,大约阅读时间需要 6 分钟。

前言

===========================================

初步接触Spring Boot

===========================================

资源文件中自定义属性值,配置在一个对象bean上,然后在程序中可以使用bean的属性值。

 一。

 

 

二。

@Component 标志本类为一个bean
@PropertySource(value = "classpath:/application.properties") 指定绑定哪个资源文件,【如果要绑定自定义的资源文件中的值的话,是可以用上的】这里的application.properties文件是springboot默认的资源文件,是可以不用指定的,这里绑定的话,会去加载绑定两次。
@ConfigurationProperties(prefix = "com.sxd") 指定绑定资源文件中前缀以com.sxd开头的属性名,其他的不会绑定过来。因为这里location属性取消了,所以采用上面注解进行替代方案

 

package com.sxd.beans;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component;@Component@PropertySource(value = "classpath:/application.properties")@ConfigurationProperties(prefix = "com.sxd")public class ConfigBean {    private String name;    private String want;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getWant() {        return want;    }    public void setWant(String want) {        this.want = want;    }}
View Code

 

 

三。

@EnableConfigurationProperties(ConfigBean.class) 激活绑定的bean
@Autowired 将绑定的某个bean自动注入

 

 

package com.sxd.firstdemo;import com.sxd.beans.ConfigBean;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@SpringBootApplication@EnableConfigurationProperties(ConfigBean.class)public class FirstdemoApplication {    @Autowired    ConfigBean configBean;    @RequestMapping("/")    public String index(){        return "Hello Spring Boot,"+configBean.getName();    }    public static void main(String[] args) {        SpringApplication.run(FirstdemoApplication.class, args);    }}
View Code

 

 四。

运行结果:

 

转载地址:http://yoyll.baihongyu.com/

你可能感兴趣的文章
jqGrid的若干种用法
查看>>
jQuery实现文本框回车键转tab键 分类: JavaScript ...
查看>>
内存程序文件、内存对齐程序
查看>>
wp7设置浏览器主页
查看>>
资源管理更新系统V2.0版的一些问题
查看>>
Sil“.NET研究”verlight与HTML双向交互
查看>>
More-iOS中的Ping
查看>>
React 重要的一次重构:认识异步渲染架构 Fiber
查看>>
TensorFlow笔记(2)——利用TensorFlow训练一个最简单的一元线性模型
查看>>
TensorFlow笔记(4)——优化手写数字识别模型之代价函数和拟合
查看>>
微服务java_b2b商城系统_java商城源码100%开源适合2次开发-(七)高可用的分布式配置中心(Spring Cloud Config)...
查看>>
Swift5.0新特性更新
查看>>
React Redux 中间件思想遇见 Web Worker 的灵感(附demo)
查看>>
超可爱的颜文字,我要放到代码里❛‿˂̵✧
查看>>
Laravel核心解读--观察者模式
查看>>
re:Invent第三天:除了拥抱混合云,AWS还一口气发了这些新产品
查看>>
精益业务分析宣言解读
查看>>
细数iOS上的那些安全防护
查看>>
H5打造属于自己的视频播放器(HTML篇)
查看>>
关于人工智能,你所需了解的基本知识
查看>>