讀取資源文件配置
pom依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
適合屬性比較少的
@Component
@PropertySource(value = {"classpath:static/config/user .properties"}, ignoreResourceNotFound = false, encoding = "UTF-8", name = "user .properties")
public class User {
@Value("${User .name}")
private String name;
@Value("${User .age}")
private int age;
}
常用方式 當使用 @Value 需要注入的值較多時,代碼就會顯得冗餘,於是 使用@ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "user ")
@PropertySource(value = {"classpath:static/config/user .properties"}, ignoreResourceNotFound = false, encoding = "UTF-8", name = "user.properties")
public class User {
private String name;
private int age;
}
@PropertySource 中的屬性解釋
1.value:指明加載配置文件的路徑。
2.ignoreResourceNotFound:指定的配置文件不存在是否報錯,默認是false。當設置爲 true 時,若該文件不存在,程序不會報錯。實際項目開發中,最好設置 ignoreResourceNotFound 爲 false。
3.encoding:指定讀取屬性文件所使用的編碼,我們通常使用的是UTF-8。
使用 @EnableConfigurationProperties 開啓 @ConfigurationProperties 註解。
@RestController
@EnableConfigurationProperties
public class DemoController {
@Autowired
User user;
@RequestMapping("/")
public String index(){
return "user name is " + user.getName() + ",user age is " + user.getAge();
}
或者直接
@Configuration
@ConfigurationProperties(prefix = "user ")
@PropertySource(value = "classpath:static/config/user.properties")
public class User {
private String name;
private int age;
}
@RestController
public class DemoController {
@Autowired
User user;
@RequestMapping("/")
public String index(){
return "user name is " + user.getName() + ",user age is " + user.getAge();
}