spring boot 读书笔记4-Spring Boot中的项目属性配置
1.少量配置信息的情形
application.yml 中配置微服务地址
url: orderUrl: http://localhost:8002
通过@value获取
@RestController @RequestMapping("/test") public class TestController { @Value("${url.orderUrl}") private String orderUrl; @RequestMapping("/config") public String testConfig(){ return orderUrl; } }
2. 多个配置信息的情形
多个配置信息的情形,
application.yml
url: orderUrl: http://localhost:8002 testUrl: http://127.0.0.1:88/test devUrl: http://127.0.0.1:8811/dev
pom.xml引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
编写实体类
需要加ConfigurationProperties,prefix指向配置,@Component,把该类作为组件放到Spring容器中
@Component @ConfigurationProperties(prefix ="url") public class MicroServiceUrl { private String orderUrl; private String testUrl; private String devUrl; public void setDevUrl(String devUrl) { this.devUrl = devUrl; } public String getDevUrl() { return devUrl; } public String getOrderUrl() { return orderUrl; } public void setOrderUrl(String orderUrl) { this.orderUrl = orderUrl; } public String getTestUrl() { return testUrl; } public void setTestUrl(String testUrl) { this.testUrl = testUrl; } }
通过@Resource 将写好的配置类注入进来
@RestController @RequestMapping("/test") public class TestController { @Resource private MicroServiceUrl microServiceUrl; @RequestMapping("/order") public String orderConfig(){ return microServiceUrl.getOrderUrl(); } @RequestMapping("/test") public String testConfig(){ return microServiceUrl.getTestUrl(); } @RequestMapping("/dev") public String devConfig(){ return microServiceUrl.getDevUrl(); }
3. 指定项目配置文件
两个配置文件,配置不同环境
application-dev.yml
application-pro.yml
application.yml指定选用哪个即可
spring: profiles: active: - dev