读取资源文件配置
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();
}