今天主要说下,配置在resources文件中的内容怎样被spring boot所引用。
- 引用静态模板的值
- thymeleaf和spring boot的整合,及相关配置
根据springboot 推荐的格式,我们知道放在resources 都是一些资源,包括整个项目的配置啊 ,自定义配置啊 ,静态资源文件 (js,css等),以properties结尾。字面意思就是属性暂且就这么翻译吧。
application.properties是项目资源的配置,比如jar包的配置啊,比如默认端口是8080 但是我们想改成其他端口,怎么办了。只需要在这个系统配置文件里加上
server.port=端口号
当然,还有很多其他的方法,但是有这个简单吗。
下面来做个实例来演示如何把一个定义在静态资源文件的值映射到一个对象上;
- 新建一个com.xiaofeng.feng.pojo包,添加实体类Resource.java:
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里面新添加一个类成员变量
@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>
thymeleaf
在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要高。
文章仅作为学习笔记,没有令人拍案叫绝的精彩剖析,没有深入浅出的长篇巨著。如果没有帮到您,抱歉。如果一不小心解开了您的困惑。非常荣幸。仅以此篇共勉。也感谢那些我读过的博客和看过的视频。 厚德载物,自强不息!