spring boot 引入模板,springboot
今天主要說下,配置在resources檔案中的內容怎樣被spring boot所引用。
- 引用靜態模板的值
- thymeleaf和spring boot的整合,及相關配置
根據springboot 推薦的格式,我們知道放在resources 都是一些資源,包括整個項目的配置啊 ,自訂配置啊 ,靜態資源檔案 (js,css等),以properties結尾。字面意思就是屬性暫且就這麼翻譯吧。
application.properties是項目資源的配置,比如jar包的配置啊,比如預設連接埠是8080 但是我們想改成其他連接埠,怎麼辦了。只需要在這個系統設定檔裡加上
server.port=連接埠號碼
當然,還有很多其他的方法,但是有這個簡單嗎。
下面來做個執行個體來示範如何把一個定義在靜態資源檔案的值對應到一個對象上;
package com.xiaofeng.feng.pojo;
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裡面新添加一個類成員變數
@Autowiredprivate 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>thymeleaf
在application.properties種配置如下
spring.thymeleaf.prefix=classpath:/templates/ /*模板的位置 這裡是在resources/templates下*/spring.thymeleaf.cache=falsespring.thymeleaf.encoding=UTF-8spring.thymeleaf.mode=HTML5spring.thymeleaf.content-type=text/htmlspring.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要高。