SpringBoot属性资源文件配置
1.在pomxml文件中引入资源文件的读取需要依赖的包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.资源文件目录和内容如下:
内容如下:com.iben.opensource.name=iben com.iben.opensource.website=www.iben.com com.iben.opensource.language=java在这里插入代码片
3.写一个对应于资源文件的POJO类,代码如下:在这里插入代码片
package com.iben.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration //代表引用资源文件,代表这是一个配置
@ConfigurationProperties(prefix = “com.iben.opensource”)//注入这个前缀后面的字段到声明变量里面来
@PropertySource(value = “classpath:resource.properties”)//资源文件的配置
public class Resource {
private String name;
private String website;
private String language;
public Resource() {
super();
}
public Resource(String name, String website, String language) {
super();
this.name = name;
this.website = website;
this.language = 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;
}
@Override
public String toString() {
return “Resource [name=” + name + “, website=” + website + “, language=” + language + “]”;
}
}
4.测试:
package com.iben.Controller;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.iben.pojo.JSONResult;
import com.iben.pojo.Resource;
@RestController
public class HelloController {
@Autowired
private Resource resource;
@RequestMapping("/getResource")
public JSONResult getResource() {
Resource bean=new Resource();
BeanUtils.copyProperties(resource, bean);
return JSONResult.ok(bean);
}
}
在浏览器中输入http://127.0.0.1:8080/getResource即可看到对应的结果