1. 程式人生 > 其它 >spring boot 讀書筆記4-Spring Boot中的專案屬性配置

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