1.从spring boot默认的application.properties资源文件中获取
方法一:使用@value注解
1) application.properties文件中定义属性,如
test=aaa
2) 采用@value注解方式使用
@Value("${application.test}")
private String msg;
方法二:当属性太多时,一个个绑定到属性字段上太累,此时可以将所有属性封装到一个类中
1) application.properties中属性为
application.test1=aaa
application.test2=bbb
2)定义一个配置文件的类
@ConfigurationProperties(prefix="application")
public class ApplicationProperties {
private String test1;
private String test2;
public String getTest1() {
return test1;
}
public void setTest1(String test1) {
this.test1 = test1;
}
public String getTest2() {
return test2;
}
public void setTest2(String test2) {
this.test2 = test2;
}
}
注意加上此注解,@ConfigurationProperties(prefix=”application”),标明识别的是前缀为application的属性。
3)spring Boot入口类加上@EnableConfigurationProperties注解,使用配置文件。
4)输出结果为
test1=aaa
test2=bbb
2.从自定义资源文件中获取
2.1读取自定义properties文件
1)在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2)创建自定义资源文件resource.properties
com.swt.opensource.name = swt
com.swt.opensource.website = www.swt.com
com.swt.opensource.language = java
3)创建Resource类绑定自定义资源文件
@Configuration
@ConfigurationProperties(prefix="com.swt.opensource")
@PropertySource(value="classpath:resource.properties") //指定自定义资源文件
public class Resource {
private String name;
private String website;
private String language;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
4)写Controller类
@RestController
public class HelloController {
@Autowired
private Resource resource;
@RequestMapping("/hello")
public Object hello() {
return "hello springboot~~";
}
@RequestMapping("/getResource")
public String getResource() {
Resource bean = new Resource();
BeanUtils.copyProperties(resource, bean);
return bean.getName()+","+bean.getWebsite()+","+bean.getLanguage();
}
}
5)在主启动类中添加扫描路径
//扫描所有需要的包, 包含一些自用的工具类包所在的路径
@ComponentScan(basePackages= {"com.example"})