Spring Boot 资源文件属性配置
配置文件是指在resources根目录下的application.properties
或application.yml
配置文件,读取这两个配置文件的方法有两种,都比较简单。
在pom.xml中添加:
1 2 3 4 5 | <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional> true </optional> </dependency> |
一、资源文件属性配置直接读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * @author oyc * @Title: * @Description: * @date 2018/6/1321:44 */ @RestController @RequestMapping ( "/resource" ) public class ResourceController { @Value ( "${com.bestoyc.opensource.name}" ) private String name; @Value ( "${com.bestoyc.opensource.webSite}" ) private String webSite; @Value ( "${com.bestoyc.opensource.language}" ) private String language; @RequestMapping ( "/getResource1" ) public String GetResource1() { return "Name:" + name + "----WebSite:" + webSite + "----Language:" + language; } } |
注意:在@Value
的${}中包含的是核心配置文件中的键名。在Controller类上加@RestController
表示将此类中的所有视图都以JSON方式显示,类似于在视图方法上加@ResponseBody
。
二、资源文件中的属性配置映射到实体类中
将配置属性映射到实体类中,然后再将实体类注入到Controller或者Service中即可完成属性配置的读取。
属性配置文件(resource.properties):
1 2 3 | com.bestoyc.opensource.name=bestoyc com.bestoyc.opensource.website=www.bestoyc.com com.bestoyc.opensource.language=java |
![](https://images2018.cnblogs.com/blog/827309/201806/827309-20180613221151208-1316173460.png)
对应的实体类(Resource.java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | /** * @author oyc * @Title:资源文件映射实体类 * @Description: * @date 2018/6/13 21:32 */ @Configuration @ConfigurationProperties (prefix = "com.bestoyc.opensource" ) @PropertySource (value = "classpath:resource.properties" ) public class Resource { private String name; private String webSite; private String language; //省略getter、setter方法 } |
注意:
![](https://images2018.cnblogs.com/blog/827309/201806/827309-20180613221231129-670624039.png)
测试类(ResourceController.java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | /** * @author oyc * @Title: * @Description: * @date 2018/6/1321:44 */ @RestController @RequestMapping ( "/resource" ) public class ResourceController { @Autowired private Resource resource; @RequestMapping ( "/getResource" ) public String GetResource() { return "Name:" + resource.getName() + "----WebSite:" + resource.getWebSite() + "----Language:" + resource.getLanguage(); } } |
在SpringdemoApplication中加入@ComponentScan(basePackages= {"com.bestoyc"}),用于扫描我们的测试Controller包中的测试类方法:
![](https://images2018.cnblogs.com/blog/827309/201806/827309-20180613221636626-1386248150.png)
访问:http://localhost:8080/resource/getResource 时将得到Name:java----WebSite:www.bestoyc.com----Language:java
![](https://images2018.cnblogs.com/blog/827309/201806/827309-20180613223452991-1132172440.png)