Spring-boot provides a lot of default configuration items, but there are always some business-own configuration items in the development process, and here's an example of how to add a custom configuration:
One, write a custom configuration of the class
Package Com.example.config;import Lombok. Data;import Org.springframework.boot.context.properties.configurationproperties;import org.springframework.stereotype.component;/** * Created by the Bodhi tree under the Poplar on 2017/4/15. */@Data @component@configurationproperties (prefix = "Web. config") public class Webconfig { private String webtitle; private String AuthorName; Private String Authorblogurl;}
Note The above annotation @configurationproperties (prefix = "Web. config"), which means that the class will read the property values from the property file that begin with Web. config
Second, configure the properties in Application.yml
Spring-boot supports the properties and YML formats, but it is recommended that you use the new YML format to look clearer
Web: config: webtitle: "Welcome to Springboot" authorname: "Yang over the Bodhi tree" authorblogurl: "http://yjmyzz.cnblogs.com/"
Three, to a
To demonstrate the effect, you can get a simple Web application, first a 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";} }
Then write something in the index.html template (Note: This example uses Thymeleaf as the template engine)
<! DOCTYPE html>
The final run-up effect is as follows:
Iv. Loading order of configuration files
It is obviously not the best practice to put all the configuration in a jar package, it is more common to put the configuration file outside the jar package and modify the configuration if necessary without moving the Java code. Spring-boot will load the configuration file application.properties or application.yml in the following order:
4.1 First find the./config subdirectory under the jar file sibling directory with or without configuration file (external)
4.2 Find the jar sibling directory with no configuration file (external)
4.3 find config file under this package (built-in)
4.4 is the last to find the configuration file under Classpath (built-in)
Attached: source code Download Spring-boot-web-demo.zip
Reference article:
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-command-line-args
Spring-boot Express (4) Custom configuration