Spring Boot使用自定义的properties
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot使用自定义的properties相关的知识,希望对你有一定的参考价值。
spring boot使用application.properties默认了很多配置。但需要自己添加一些配置的时候,我们应该怎么做呢。
若继续在application.properties中添加如:
wisely.name=zhangsan
wisely.gender=male
wisely.age=20
定义配置类:
@ConfigurationProperties(prefix = "wisely")
public class WiselySettings {
private String name;
private String gender;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
注入application.properties文件中的属性
若新用新的配置文件,如新建一个wisely.properties
wisely2.name=lisi
wisely2.gender=female
wisely2.age=30
需定义如下配置类
@Configuration
@PropertySource("classpath:wisely.properties")//注意路径
public class Wisely2Settings {
@Value("${wisely2.name}")
private String name;
@Value("${wisely2.gender}")
private String gender;
@Value("${wisely2.age}")
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
@ConfigurationProperties(prefix = "wisely2",locations = "classpath:wisely.properties")
这个注解貌似已经取消了,所以这里使用@PropertySource注解
最后注意在spring Boot入口类加上@EnableConfigurationProperties
@SpringBootApplication
@EnableConfigurationProperties({WiselySettings.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Wisely2Settings.class不需要加,因为它没有使用@ConfigurationProperties注解
测试:
@Controller
public class TestController {
@Resource
WiselySettings wiselySettings;
@Resource
Wisely2Settings wisely2Settings;
@RequestMapping("/test")
public
@ResponseBody
String test() {
System.out.println("wisely.name = " + wiselySettings.getName());
System.out.println("wisely.gender = " + wiselySettings.getGender());
System.out.println("wisely.age = " + wiselySettings.getAge());
System.out.println("wisely2.name = " + wisely2Settings.getName());
System.out.println("wisely2.gender = " + wisely2Settings.getGender());
System.out.println("wisely2.age = " + wisely2Settings.getAge());
return "ok";
}
}
参考:http://412887952-qq-com.iteye.com/blog/2292728
以上是关于Spring Boot使用自定义的properties的主要内容,如果未能解决你的问题,请参考以下文章
Spring boot - Application.properties 中的自定义变量
Spring boot 的 properties 属性值配置 application.properties 与 自定义properties
spring boot 中属性注入,application.properties 自定义前缀以及使用properties 封装mysql
IDEA开发spring boot应用时 application.yml 或 application.properties 自定义属性提示