springboot中获取配置文件的方式,通常大家最常用的是@Value("${mail.username}")的形式,也可以用spring-boot-configuration-processor来更优雅得读取配置文件。下面讲下具体用法。
1、引入pom文件
在使用idea创建springboot项目的时候,可以选择。
也可以直接引入pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2、配置属性文件
author.name=zhangsan
author.age=20
3、对用的配置类 加@PropertySource("classpath:myPro.properties")。
@Component
@PropertySource(value = {"classpath:static/config/authorSetting.properties"},
ignoreResourceNotFound = false, encoding = "UTF-8", name = "authorSetting.properties")
public class Author {
@Value("${author.name}")
private String name;
@Value("${author.age}")
private int age;
}
value:加载配置文件的路径。
ignorResourceNotFound: 指定是否忽略 配置文件不存在的 报错提示。默认是false(不忽略,不存在则报错)
encoding: 指定读取属性文件所使用的编码。
当使用@value注入的属性较多时,代码会显得很冗杂,于是@ConfigurationProperties(prefix="author") 登场。
@Configuration
@EnableConfigurationProperties(Author.class)
@ConfigurationProperties(prefix = Author.PREFIX, ignoreInvalidFields = true)
@PropertySource(value = {"classpath:static/config/authorSetting.properties"},
ignoreResourceNotFound = false, encoding = "UTF-8", name = "authorSetting.properties")
public class Author {
public static final String PREFIX = "author"; // 这里对应配置文件中的mail前缀
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
编写controller层测试
@RestController
@EnableConfigurationProperties
public class DemoController {
@Autowired
Author author;
@RequestMapping("/index")
public String index(){
return "author's name is " + author.getName() + ",ahtuor's age is " + author.getAge();
}
}
注意:使用 @EnableConfigurationProperties 开启 @ConfigurationProperties 注解。
测试结果:
更多推荐
Spring Boot(三十七):Spring Boot 使用spring-boot-configuration-processor获取配置文件
发布评论