使用自定义属性
在**application.properties**文件添加以下自定义属性:
lyp.db.url=大咪咪
lyp.db.username=咪咪大
接下来,写一个类来映射刚刚写的自定义属性,从而直接通过对象获取配置文件的内容。在此处本人曾经粗心大意遇到过一个问题,那就是Spring容器里的MyProperties属性注入失败,值都是默认的,原因:粗心,忘记写set和get方法了。
@Component
@ConfigurationProperties(prefix="lyp.db")
public class MyProperties {
private String url;
private String username;
public String getUrl() {
return url;
}
public String getUsername() {
return username;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
}
@ConfigurationProperties默认从application.properties取属性,prefix为前缀,例如lyp.db.url中的lyp.db。
接下来写个Controller类测试
@RequestMapping
@RestController
public class PropertiesController {
private static final Logger logger=LoggerFactory.getLogger(PropertiesController.class);
@Autowired
private MyProperties myProperties;
@GetMapping("/p1")
public MyProperties myProperties() {
return this.myProperties;
}
}
在浏览器/Postman访问 localhost:端口号/p1,会返回
{“url”:“大咪咪”,“username”:“咪咪大”}
使用自定义配置文件
新创建application2.properties文件,名字随便起什么cat.properties,av.properties都可以,内容如下
lyp2.cup=D
lyp2.name=大咪咪
lyp2.nationality=小日本
再写个类来映射application2.properties的内容
@Component
@PropertySource("classpath:application2.properties")
@ConfigurationProperties(prefix="lyp2")
public class MyProperties2 {
private String cup;
private String name;
private String nationality;
。。。省略set和get方法,可不要忘了哦
}
@PropertySource指定映射哪个配置文件
@GetMapping("/p2")
public MyProperties2 myProperties2() {
return this.myProperties2;
}
在浏览器/Postman访问 localhost:端口号/p2,会返回
{“cup”:“D”,“name”:“大咪咪”,“nationality”:“日本”}
Profile多环境配置
一般在企业中都会有开发环境/测试环境/正式环境,不同环境下的配置信息肯定不一致的,例如数据库连接,redis,MQ等。哈哈,此时就轮到spring.profile.active来发挥啦。之前默认的配置文件名为application.properties,多环境下的配置文件命名格式需要按照如下格式:application-{profile}.properties。
接下来咱们创建application-dev.properties,application-test.properties,application-prod.properties,这三个文件的属性名要保持一致,免得出问题。分别加上如下内容
application-dev.properties
server.servlet.context-path=/dev
application-test.properties
server.servlet.context-path=/test
application-prod.properties
server.servlet.context-path=/prod
server.servlet.context-path是指定项目路径的,在application.properties增加spring.profiles.active=test属性,重启项目,访问 localhost:端口/test/p1
会返回
{“url”:“test”,“username”:“咪咪大”}
说明生效的是application-test.properties,如果想切换成dev/prod,把application.properties的spring.profiles.active属性值改成对应的dev/prod即可。但是一般很少这样操作,下面介绍另一种灵活切换配置文件的方法。
- 先把利用maven将项目打包(自行百度)
- 在target目录下找到打包后的jar文件
- 打开命令行,并且指定配置文件的对应属性:java -jar 项目jar包路径 --spring.profiles.active=test --lyp.db.url=lyp_test --lyp.db.username=ok
访问 localhost:端口/test/p1,会返回
{“url”:“lyp_test”,“username”:“ok”}。
总结
本文主要讲解了@ConfigurationProperties以及prefix、@PropertySource的用法,编写自定义配置,通过命令来引导配置。
此文章是本人根据他人的作品稍作修改写的,主要用于记录在学习路上遇到的一些问题,如有错漏之处,敬请指正!
参考出处:https://blog.battcn.com/2018/04/22/springboot/v2-config-properties/