SpringBoot默认的配置文件为application.properties或者application.yml,应用启动时会自动加载此文件,无需手动引入。
在
application.properties
中定义属性值
#自定义属性 rumenz.name=rumenz rumenz.url=https://rumenz.com
通过
@Value
注解来获取值
@RestController @RequestMapping("/rumenz") public class RumenzController { @Value("${rumenz.name}") private String rumenzName; @Value("${rumenz.url}") private String rumenzUrl; @RequestMapping("/index") public String index(){ return rumenzName+":::"+rumenzUrl; } }
访问
http://127.0.0.1:8080/rumenz/index
路径,会返回rumenz:::https://rumenz.com
。
有时间有需要注入的属性比较多,一个一个绑定很繁琐,官方建议通过Bean的方式加载。
application.properties配置文件定义属性值
com.rumenz.id=1 com.rumenz.name=hello
RumenzConfig配置文件
@Component @ConfigurationProperties(prefix = "com.rumenz") public class RumenzConfig { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
浏览器输入
http://127.0.0.1:8080/rumenz/index1
,返回1:::hello
@RestController @RequestMapping("/rumenz") public class RumenzController { @Autowired RumenzConfig rumenzConfig; @RequestMapping("/index1") public String index1(){ return rumenzConfig.getId()+":::"+rumenzConfig.getName(); } }
在application.properties中的各个参数之间可以直接引用来使用
com.rumenz.id=1 com.rumenz.name=hello com.rumenz.des=${com.rumenz.name}${com.rumenz.id}
新建
RumenzController
测试
@RestController @RequestMapping("/rumenz") public class RumenzController { @Value("${com.rumenz.des}") private String rumenzDes; @RequestMapping("/index2") public String index2(){ //配置文件参数引用 //com.rumenz.des=${com.rumenz.name}${com.rumenz.id} return rumenzDes; } }
浏览器访问
http://127.0.0.1:8080/rumenz/index2
返回hello1
一般的配置项都在
application.properties
中,很多时候有一些配置信息我们想单独存放。比如我们创建了一个rumenz.properties
的自定义配置文件。
com.rumenz.tag=入门小站 com.rumenz.txt=这是一个教程网站
自定义的配置文件系统不会自动加载,需要用
@PropertySource
加载。需要加载多个可以用设置数组。
测试
@RestController @RequestMapping("/rumenz") @PropertySource(value="classpath:rumenz.properties",encoding = "utf-8") public class Rumenz1Controller { @Value("${com.rumenz.tag}") private String rumenzTag; @Value("${com.rumenz.txt}") private String rumenzTxt; @RequestMapping("/index3") public String index3(){ //这是自定义配置中配置的属性 return rumenzTag+rumenzTxt; } }
浏览器访问
http://127.0.0.1:8080/rumenz/index3
,返回入门小站这是一个教程网站
@PropertySource(value = { "classpath:rumenz.properties", "classpath:rumenz2.properties", }, encoding = "utf-8")
本小结源码地址:
介绍