Scenario: During project deployment, the spring boot profile is not well understood until the project has a puzzling problem-the configuration file in the project classes is overwritten and the program starts up with an error!
1 Prioritization of configuration files
Application.properties Everyone is not strange, when we are developing, we often use it to configure some variables that can be manually modified and not compiled, the effect is that when the war package or jar for the production environment, we can manually modify the environment variables without recompiling.
Spring Boo has already configured many environment variables by default, for example, Tomcat's default port is 8080, the project's ContextPath is "/", and so on, you can see Spring boot default configuration information here http://docs.spring.io/ spring-boot/docs/current-snapshot/reference/htmlsingle/#boot-features-external-config
1.1 Configuring Item reading order
- Command-line arguments
- Value set by Spring_application_json
- JNDI attributes from Java:comp/env
- Java System Properties (
System.getProperties() )
- Operating system Environment variables
- A Randomvaluepropertysource that is only have properties in random.*.
- Profile-related profiles outside the project Jar (application-{profile}.properties)
- Profile-related profiles within jars (application-{profile}.properties)
- Configuration file outside the project Jar (application.properties)
- Configuration file within Jar (application.properties)
@PropertySourceAnnotations on your @Configuration classes.
- Default Property (
SpringApplication.setDefaultProperties )
1.2 Application.properties Find Location
In addition to the application.properties configuration parameters, there are several ways to set parameters. Spring Boot finds the configuration items in the following order:
Spring boot allows you to customize a application.properties file and then place it in the following places to override the spring boot environment variables or define your own environment variables
Spring Boot finds the Application.properties file from 4 locations by default.
- /config directory under the current directory
- Current directory
- /config directory under the Classpath
- Class Path root directory
Description
当前目录Refers to the directory where the jar file is run, not necessarily the directory where the jar file is located, and all the top 2 items above are jar out-of-package catalogs.
If you have a configuration file in four places at the same time, the profile is prioritized from 1 to 4.
- Current directory, currently does not know how to determine, but spring will display the current directory when it is started:
Depending on the xxxapplicationstarter, you can navigate to the current directory. Then configure the configuration file as needed.
That is the classes directory.
1.3 Reading and setting configuration file properties
Reference article http://www.nathanyan.com/2016/01/25/Spring-Boot-04-%E9%85%8D%E7%BD%AE%E7%9B%B8%E5%85%B3/
With the configuration file, when Spring Boo starts, it automatically reads the configuration information into the spring container and overrides the default configuration of spring boot, so how do we read and set these configuration information?
1. Override and configure environment variables by command line with the highest priority, for example, you can override the spring boot embedded Tomcat service port with the following command, noting that there are no spaces between the two sides
Java-jar Demo.jar--server.port=9000
If you want to set multiple variables, you can set the JSON format string
Java-jar Demo.jar--spring.application.json= ' {"foo": "Bar"} '
2. Read by @value annotations
@RestController @requestmapping ("/task") Public class Taskcontroller {@Value (private= {"/", ""}) public String helltask (@ Value ("${connection.username}") String name { return "Hello task!!") ;}}
3. Through the environment interface to obtain, only need to put the interface in the
@RestController @requestmapping ("/task") Public class Taskcontroller {@Autowired environment ev; @Value (private= {"/", ""})public string Helltask (@Value ("${connection.username}") string name) { = Ev.getproperty (" Connection.password "); return "Hello Task!" ;}}
4. A tool class can be customized to obtain, the key is to read the configuration file information, suitable for custom configuration information, the spring container default configuration information will not be read
@Component Public classSystemconfig {Private StaticProperties props; PublicSystemconfig () {Try{Resource Resource=NewClasspathresource ("/application.properties");//Props =propertiesloaderutils.loadproperties (Resource); } Catch(IOException e) {e.printstacktrace (); } } /*** Get Properties *@paramKey *@return */ Public Staticstring GetProperty (String key) {returnProps = =NULL?NULL: Props.getproperty (key); } /*** Get Properties *@paramKey Property Key *@paramDefaultValue Property Value *@return */ Public Staticstring GetProperty (String key,string defaultvalue) {returnProps = =NULL?NULL: Props.getproperty (Key, DefaultValue); } /*** Get properyies Properties *@return */ Public StaticProperties getProperties () {returnprops; }}//If you use it, you can do it directly .String value = Systemconfig.getproperty ("key");
5. Can take advantage of ${...} Referencing variables in application.properties
Myapp.name=springmyapp.desc=${myapp.name} nice
6. You can configure random variables in application.properties, using the Randomvaluepropertysource class
my.secret=${random.value}my.number=${random. int}my.bignumber=${random. Long}my.number.less.than.ten=${random. int(Ten)}my.number.in.range=${random. int[1024,65536]}
7. Binding attribute values to beans
Yaml file
propertiesFiles are a bit inappropriate when confronted with hierarchical data. YAML supports a JSON-like format that can represent hierarchical data. See here for detailed instructions.
The contents of Yaml are converted to the properties format, as follows:
environments: Dev: url:http://dev.bar.com name:developer Setup Prod: url:http://foo.bar.com name:my Cool appmy: servers : - dev.bar.com -foo.bar.com
Environments.dev.url=http://dev.bar.comenvironments.dev.name=Developer Setupenvironments.prod.url=http://foo.bar.comenvironments.prod.name=My Cool appmy.servers[0]=dev.bar.commy.servers[1]=foo.bar.com
Can be @Value("${environments.dev.url}") injected with.
One feature of YAML is the ability to combine configuration items from multiple files into a single file. by --- separating.
Server: 192.168.1.100---spring: profiles:developmentserver: 127.0.0.1---spring: Profiles:productionserver: 192.168.1.120
In combination, spring.profiles you can specify which configuration item to use under Profile.
Spring Boot also supports the profile feature, which is named as: application-{profile}.properties , you can use spring.profiles.active to activate profiles:
Java-jar Target/demo-0.0.1-snapshot.jar--spring.profiles.active=test
Although it is possible to @Value("${property}") inject attribute values, if there are multiple needs to inject, it is a bit of a hassle. @ConfigurationPropertiesYou can bind multiple property values directly to the bean.
Configuration file:
# application.ymlconnection: username:admin 192.168.1.1
Use:
@Component @configurationproperties (prefix= "Connection") Public class connectionsettings { private String username; Private inetaddress remoteaddress; // ... getters and Setters}
You can also inject when you create a bean:
@ConfigurationProperties (prefix = "foo") @Bean public foocomponent foocomponent () { ...}
3
Spring Boot configuration file application