首页 > 代码库 > spring-boot 速成(4) 自定义配置

spring-boot 速成(4) 自定义配置

spring-boot 提供了很多默认的配置项,但是开发过程中,总会有一些业务自己的配置项,下面示例了,如何添加一个自定义的配置:

一、写一个自定义配置的类

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格式,看上去更清晰

web:  config:    webTitle: "欢迎使用SpringBoot"    authorName: "菩提树下的杨过"    authorBlogUrl: "http://yjmyzz.cnblogs.com/"

 

三、来一发

为了演示效果,可以弄一个最简单的web应用,先来一个controller

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;@Controllerpublic 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做为模板引擎)

<!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://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-command-line-args

spring-boot 速成(4) 自定义配置