今天主要说下,配置在resources文件中的内容怎样被spring boot所引用。
根据springboot 推荐的格式,我们知道放在resources 都是一些资源,包括整个项目的配置啊 ,自定义配置啊 ,静态资源文件 (js,css等),以properties结尾。字面意思就是属性暂且就这么翻译吧。
application.properties是项目资源的配置,比如jar包的配置啊,比如默认端口是8080 但是我们想改成其他端口,怎么办了。只需要在这个系统配置文件里加上
server.port=端口号
当然,还有很多其他的方法,但是有这个简单吗。
下面来做个实例来演示如何把一个定义在静态资源文件的值映射到一个对象上;
比较简单,定义了三个属性: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下新建一个
<!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要高。
如对本文有疑问, 点击进行留言回复!!
Algebra:Chapter 0 - 预备知识: 集合论和categories
springboot + vue上传图片在服务器并实现在线预览
请谨慎使用增强for循环,刚接触Java值得一看(手动狗头)
【Nginx】还不会使用Nginx解决跨域问题?肝这一篇就够了!!
网友评论