spring默認使用yml中的配置,但有時候要用傳統的xml或properties配置,就需要使用spring-boot-configuration-processor了
引入pom依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
author.name=zhangsan author.age=20
再在配置類開頭加上@PropertySource("classpath:your.properties"),其余用法與加載yml的配置一樣
@Component @PropertySource(value = {"classpath:static/config/authorSetting.properties"}, ignoreResourceNotFound = false, encoding = "UTF-8", name = "authorSetting.properties") public class AuthorTest { @Value("${author.name}") private String name; @Value("${author.age}") private int age; }
@PropertySource 中的屬性解釋
1.value:指明加載配置文件的路徑。
2.ignoreResourceNotFound:指定的配置文件不存在是否報錯,默認是false。當設置為 true 時,若該文件不存在,程序不會報錯。實際項目開發中,最好設置 ignoreResourceNotFound 為 false。
3.encoding:指定讀取屬性文件所使用的編碼,我們通常使用的是UTF-8。
當我們使用 @Value 需要注入的值較多時,代碼就會顯得冗余,於是 @ConfigurationProperties 登場了
@Component @ConfigurationProperties(prefix = "author") @PropertySource(value = {"classpath:static/config/authorSetting.properties"}, ignoreResourceNotFound = false, encoding = "UTF-8", name = "authorSetting.properties") public class AuthorTest { private String name; private int age; }
@RestController @EnableConfigurationProperties public class DemoController { @Autowired AuthorTest authorTest; @RequestMapping("/") public String index(){ return "author's name is " + authorTest.getName() + ",ahtuor's age is " + authorTest.getAge(); } }
使用 @EnableConfigurationProperties 開啟 @ConfigurationProperties 注解。