今天主要說下,配置在resources文件中的內容怎樣被spring boot所引用。
根據springboot 推薦的格式,我們知道放在resources 都是一些資源,包括整個項目的配置啊 ,自定義配置啊 ,靜態資源文件 (js,css等),以properties結尾。字面意思就是屬性暫且就這么翻譯吧。
application.properties是項目資源的配置,比如jar包的配置啊,比如默認端口是8080 但是我們想改成其他端口,怎么辦了。只需要在這個系統配置文件里加上
server.port=端口號
當然,還有很多其他的方法,但是有這個簡單嗎。
下面來做個實例來演示如何把一個定義在靜態資源文件的值映射到一個對象上;
- 新建一個com.xiaofeng.feng.pojo包,添加實體類Resource.java:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@ConfigurationProperties(prefix="com.xiaofeng.feng")
@PropertySource(value="classpath:response.properties")
public class Resource {
private String name;
private String website;
private String language;
public String getName() {
return this.name;
}
public String getWebsite(){
return this.website;
}
public String getLanguage(){
return this.language;
}
public void setName(String name) {
this.name=name;
}
public void setWebsite(String website){
this.website = website;
}
public void setLanguage(String language){
this.language = language;
}
}
比較簡單,定義了三個屬性:name,website,language;
2.然后在resources下新建一個資源文件:resource.properties 定義如下:

3.在HelloWorldController里面新添加一個類成員變量
@Autowired private Resource resource;
在寫一個方法看下返回結果:
@RequestMapping("/getResource")
public Object getResource(){
Resource bean=new Resource();
BeanUtils.copyProperties(resource, bean);
return bean;
}
得到結果:

說明資源文件的內容已經成功映射到我們定義的類中了。
這個是為什么了,主要是
@Configuration @ConfigurationProperties(prefix="com.xiaofeng.feng1") @PropertySource(value="classpath:response.properties")
定義映射關系
Resource bean=new Resource(); BeanUtils.copyProperties(resource, bean);
綁定具體的值。
在這里順帶說下freemarker和thymeleaf 2種模板展示模板在spring boot中的整合。
thymeleaf
需要在pom.xml引入thymeleaf 包的引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在application.properties種配置如下
spring.thymeleaf.prefix=classpath:/templates/ /*模板的位置 這里是在resources/templates下*/ spring.thymeleaf.cache=false spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.mode=HTML5 spring.thymeleaf.content-type=text/html spring.thymeleaf.suffix=.html
新建一個ThymeleafController 實現如下:
@RequestMapping("/index")
public String index(ModelMap map){
map.addAttribute("name", "thymeleaf xiaofeng");
return "thymeleaf/index";
}
在templates/thymeleaf下新建一個index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"></meta>
<title>Insert title here</title>
</head>
<body>
Thymeleaf 模板引起
<h1 th:text="${name}">hello world~~</h1>
</body>
</html>
注意標簽對要寫好 要不然會出錯。
運行結果如下:

個人是比較推薦使用thymeleaf這個模板的,freemarker和它使用差不多,但是耦合比thymeleaf要高。
