spring-boot 速成(4) 自定义配置
spring-boot 提供了很多默认的配置项,但是开发过程中,总会有一些业务自己的配置项,下面示例了,如何添加一个自定义的配置:
一、写一个自定义配置的类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package com.example.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * Created by 菩提树下的杨过 on 2017/4/15. */ @Data @Component @ConfigurationProperties (prefix = "web.config" ) public class WebConfig { private String webTitle; private String authorName; private String authorBlogUrl; } |
注意上面的注解@ConfigurationProperties(prefix = "web.config"),这表示这个类将从属性文件中读取web.config开头的属性值
二、在application.yml中配置属性
spring-boot支持properties及yml格式,不过推荐大家使用新的yml格式,看上去更清晰
1 2 3 4 5 | web: config: webTitle: "欢迎使用SpringBoot" authorName: "菩提树下的杨过" authorBlogUrl: "http://yjmyzz.cnblogs.com/" |
三、来一发
为了演示效果,可以弄一个最简单的web应用,先来一个controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package com.example.controllers; import com.example.config.WebConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @Autowired WebConfig webConfig; @RequestMapping ( "/" ) String index(ModelMap map) { map.addAttribute( "title" , webConfig.getWebTitle()); map.addAttribute( "name" , webConfig.getAuthorName()); map.addAttribute( "blog" , webConfig.getAuthorBlogUrl()); return "index" ; } } |
然后在index.html模板中写点东西(注:本例使用了thymeleaf做为模板引擎)
1 2 3 4 5 6 7 8 9 10 11 12 | <! DOCTYPE html> < html xmlns:th="http://www.thymeleaf.org"> < head > < title th:text="${title}"></ title > </ head > < body > < div > < h1 th:text="${name}"/> < h1 th:text="${blog}"/> </ div > </ body > </ html > |
最后跑起来的运行效果如下:
四、配置文件的加载顺序
把所有配置全都打在一个jar包里,显然不是最好的做法,更常见的做法是把配置文件放在jar包外面,可以在需要时,不动java代码的前提下修改配置,spring-boot会按以下顺序加载配置文件application.properties或application.yml:
4.1 先查找jar文件同级目录下的 ./config 子目录 有无配置文件 (外置)
4.2 再查找jar同级目录 有无配置文件(外置)
4.3 再查找config这个package下有无配置文件(内置)
4.4 最后才是查找classpath 下有无配置文件(内置)
附:源代码下载 spring-boot-web-demo.zip
参考文章:
作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步