SpringCloud SpringBoot mybatis 分散式微服務(二十)Spring Boot 自定義配置檔案
阿新 • • 發佈:2019-02-12
上面介紹的是我們都把配置檔案寫到application.yml中。有時我們不願意把配置都寫到application配置檔案中,這時需要我們自定義配置檔案,比如test.properties:
com.forezp.name=forezp
com.forezp.age=12
怎麼將這個配置檔案資訊賦予給一個javabean呢?
@Configuration @PropertySource(value = "classpath:test.properties") @ConfigurationProperties(prefix = "com.forezp") public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
在最新版本的springboot,需要加這三個註解。@Configuration
@PropertySource(value = “classpath:test.properties”)
@ConfigurationProperties(prefix = “com.forezp”);在1.4版本需要
PropertySource加上location。
@RestController @EnableConfigurationProperties({ConfigBean.class,User.class}) public class LucyController { @Autowired ConfigBean configBean; @RequestMapping(value = "/lucy") public String miya(){ return configBean.getGreeting()+" >>>>"+configBean.getName()+" >>>>"+ configBean.getUuid()+" >>>>"+configBean.getMax(); } @Autowired User user; @RequestMapping(value = "/user") public String user(){ return user.getName()+user.getAge(); } }
啟動工程,開啟localhost:8080/user;瀏覽器會顯示:
forezp12
四、多個環境配置檔案
在現實的開發環境中,我們需要不同的配置環境;格式為application-{profile}.properties,其中{profile}對應你的環境標識,比如:
- application-test.properties:測試環境
- application-dev.properties:開發環境
- application-prod.properties:生產環境
怎麼使用?只需要我們在application.yml中加:
spring:
profiles:
active: dev
其中application-dev.yml:
server:
port: 8082
啟動工程,發現程式的埠不再是8080,而是8082。