《深入理解Spring Cloud与微服务构建》学习笔记(三)~自定义配置文件
假如我们的配置文件不止一个,这时候我们就需要将配置文件对应到类。
一、例如在src/main/resources 目录下定义一个test.properties文件,配置如下:
weixin.appid = "111111"
weixin.seckey = "22222"
alipay.appid="33333"
alipay.seckey="4444"
要将此配置文件赋给jiavaBean,需要在类上加以下三个注解:@Configuration、@PropertySource、@ConfigurationProperties ,需要注意的是SpringBoot在1.4及以前则需要在@PropertySource注解上加location,并指明该配置文件的路径,当前采用SpringBoot1.5,如下:
按照学习的过程,在@ConfigurationProperties定义了前缀,那么在类里只需要定义属性就可以,至于为什么现在还不明白,反正照搬能看明白就行。
二、继续在上一次的ConfigController里进行完善,在@EnableConfigurationProperties 上添加自定义的javaBean,并注解自动装配TestBean,打印信息,如:
@RestController
@EnableConfigurationProperties({ConfigBean.class, TestBean.class})
public class ConfigController {
@Autowired
ConfigBean configBean ;
@Autowired
TestBean testBean ;
@GetMapping("config")
public String init(){
StringBuffer sb = new StringBuffer();
sb.append("***************"); sb.append("<br>");
sb.append("type="+configBean.getType()); sb.append("<br>");
sb.append("username="+configBean.getUsername()); sb.append("<br>");
sb.append("password="+configBean.getPassword()); sb.append("<br>");
sb.append("**********end************"); sb.append("<br>");
sb.append("*******test bean********"); sb.append("<br>");
sb.append("weixin_appid="+testBean.getAppid()); sb.append("<br>");
sb.append("weixin_seckey="+testBean.getSeckey()); sb.append("<br>");
sb.append("**********end************");
return sb.toString();
}
}
三、重新启动服务,浏览器访问http://localhost:8080/config,效果如:
四、 在实际开发过程中,我们有可能会有多个不同环境的配置,如:开发环境、测试环境、生产环境,SpringBoot支持 在 application.yml 中指定环境的配置文件。
配置文件的格式为:application-{profile}.properties,其中{profile}对应环境标识,例如:
application-test.properties一一测试环境;
application-dev.properties一一开发环境;
application-prod.properties一一生产环境。
我们只需要在application中加上 spring.profiles.active的配置文件,即可指定采用哪个配置文件,如下:
//application.properties 配置文件格式
spring.profiles.active = test
//application.yml配置格式
spring:
profiles:
active: dev
一般来说我们都会统一配置文件,不会两个文件里同时配置,如果两个里同时配置,那么系统系统启动会优先使用properties里的配置。
现测试配置如下:
启动系统,会发现系统启用的application-test.properties配置文件,启动了端口8088,http://localhost:8088/config
如果把application.properties里的配置删除了,系统会启动application.yml里的配置,启动开发环境配置文件。