Spring Boot Configuration Priority order

Source: Internet
Author: User
Tags tmp folder ruby on rails

Http://www.cnblogs.com/softidea/p/5759180.html

Generally in a project, there will always be a lot of environments. Like what:

Production environment, pre-release environment, test environment, development environment

The configuration files on each environment are always different, and even the environment of each developer in the development environment may be a little differently, and configuring reading is a bit of a headache.

Spring Boot provides a mechanism of priority configuration reading to help us get out of this dilemma.

In general, we all know that spring boot configuration is read from application.properties . In fact, a resource file read from the directory application.properties is a link in the Spring boot configuration chain.

Externally-configured configuration

Managing configurations in your app is not an easy task, especially if your application needs to be deployed to multiple environments. Typically, you will need to provide a corresponding property file for each environment to configure your own database connection information, server information, and third-party service accounts. A common application deployment will include several environments such as development, testing, and production. There is an overlay relationship between the configurations of different environments. The configuration in the test environment overrides the development environment, and the configuration in the production environment overrides the test environment. The Spring framework itself provides a variety of ways to manage configuration properties files. You can use Propertyplaceholderconfigurer before Spring 3.1.
Spring 3.1 introduces a new environment (environment) and profile API, which is a more flexible way to handle different environments and configuration files. However, the problem with these configuration management methods in Spring is that there are too many choices to make developers at a loss. Spring Boot provides a unified way to manage the configuration of your app, allowing developers to define different priority configuration values using property files, YAML files, environment variables, and command-line parameters.

The configuration priority order provided by Spring Boot is more complex. In order of precedence from highest to lowest, the specific list is as follows.

    1. command-line arguments.
    2. The Java system parameters obtained through System.getproperties ().
    3. Operating system environment variables.
    4. The JNDI attribute obtained from java:comp/env.
    5. The "random.*" property generated by Randomvaluepropertysource.
    6. apply The properties file outside of the Jar file . (via spring.config.location parameter)
    7. Apply the properties file inside the Jar file.
    8. A property file that is declared through the "@PropertySource" annotation in the application Configuration Java class (the Java class that contains the "@Configuration" annotations).
    9. The default property declared by the "Springapplication.setdefaultproperties".

This configuration priority of Spring Boot may seem complicated, but it's quite reasonable. For example, command-line parameters are set to the highest priority.
The benefit is that you can quickly modify configuration parameter values in a test or production environment without having to repackage and deploy the app.

The Springapplication class defaults toconverting command-line arguments that begin with "--" into configuration parameters that can be used in the app , such as "--name=alex" The value of the configuration parameter "name" is set to "Alex". If this feature is not required, you can use the springapplication. setaddcommandlineproperties(FALSE) "Disables parsing of command-line arguments.

Randomvaluepropertysource can be used to generate a variety of different types of random values required for testing, eliminating the hassle of generating in code. Randomvaluepropertysource can generate numbers and strings. The type of the number contains int and long, which can limit the size range of the number. With "random." The configuration property name as a prefix is generated by Randomvaluepropertysource, as shown in code Listing 3.

Listing 3. Configuration properties generated by using Randomvaluepropertysource
User.id=${random.value}user.count=${random.int}user.max=${random.long}user.number=${random.int (}user.range) =${RANDOM.INT[100, 1000]}
Properties file

Property files are the most common way to manage configuration properties. The Springapplication class provided by Spring Boot will search for and load the Application.properties file to get the configuration property values. The Springapplication class searches for the file in the following location.

    • The "/config" subdirectory of the current directory.
    • The current directory.
    • The "/config" package in Classpath.
    • Classpath

The above order also indicates the priority of the properties file that is contained in the location. Priority is arranged in order from highest to lowest. You can specify a different property file name by using the "Spring.config.name" configuration property. You can also use "spring.config.location" To add additional properties to the file's search path . If you have multiple profiles in your app, you can define individual properties files for each profile and name them according to "Application-{profile}".

For configuration properties, you can use "@Value" in your code, as shown in Listing 4.

Listing 4. Using the configuration properties with "@Value"
@RestController @enableautoconfigurationpublic class Application {@Value ("${name}") private String name; Requestmapping ("/") String Home () {return String.Format ("Hello%s!", name);}}

In code Listing 4, the value of the variable name comes from the "name" property in the configuration property.

Yaml

YAML is a better configuration file format relative to the properties file. YAML is well-used in Ruby on Rails. The Springapplication class also provides support for YAML configuration files, just adding a dependency on the Snakeyaml. Code Listing 5 shows an example of the Application.yml file.

Listing 5. Configuration properties expressed with YAML
Spring:profiles:developmentdb:url:jdbc:hsqldb:file:testdb username:sa Password:---spring:profiles:testdb:url:jdb C:mysql://localhost/test username:test Password:test

The Yaml file in Listing 5 also gives the configuration information for the development and test two different profiles, which is one of the advantages of the Yaml file relative to the properties file. In addition to using the @Value annotation binding to configure property values, you can use a more flexible approach. The Code Listing 6 shows the Java class that uses the YAML file in code Listing 5. With the @ConfigurationProperties (prefix= "db") annotation, the attribute value prefixed with "DB" in the configuration attribute is automatically bound to a domain of the same name in the Java class, such as the value of the URL field corresponding to the property "Db.url". You can enable the auto-bind feature by simply adding the "@EnableConfigurationProperties" annotation to the app's configuration class.

Listing 6. Java classes that use YAML files
@Component @configurationproperties (prefix= "DB") public class Dbsettings {private string URL; private string username; private String password;}
Http://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/index.html

This means that if spring boot finds the configuration in a higher priority location , it ignores the low-priority configuration .

For example, I application.properties write the configuration of the local MySQL in the directory:

db.jdbc.driver=com.mysql.jdbc.Driverdb.jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8db.jdbc.username=usernamedb.jdbc.password=password

During the commissioning phase of your project, the project will always use the local MySQL database. And once packaged, declare one externally test_evn.properties .

When you start the jar package, specify an external configuration file:

java -jar demo.jar --spring.config.location=/path/test_evn.properties

In this way, we always use our own configuration on the developer's machine, and one to the corresponding environment, we will use the configuration of the advanced location.

It is also very convenient to read these configurations in code, in the logic of the code, it is not necessary to care about where the configuration comes from, only with the attention can get what configuration is enough.

Publicclass Applicationconfigure {@Value ("${db.jdbc.driver } ") private String Jdbcdriver; @Value ("${db.jdbc.url}" ) private String Jdbcurl; @Value ("${db.jdbc.username}" ) private String Jdbcusername; @Value ("${db.jdbc.password}" ) private String Jdbcpassword; // MySQL config class //  .....              /span>      

Sometimes when we start the project, we always need to start some initialization classes, the previous common practice is to write the static block, Spring Boot provides an CommandLineRunner interface, the implementation of this interface class will always be priority to start, and prioritize the implementation CommandLineRunner of the interface provided in the run() Method.

PublicClass ApplicationconfigureImplementsCommandlinerunner {@Value ("${db.jdbc.driver}")PrivateString Jdbcdriver; @Value ("${db.jdbc.url}")private String Jdbcurl; @Value ("${db.jdbc.username}" Span style= "color: #000000;" >) private String Jdbcusername; @Value ("${ Db.jdbc.password} ") private  String Jdbcpassword; // MySQL config class //  .....  @Override public void Run (String ... strings) throws Exception {// pre-loaded with some methods, classes, properties.             /span>       

If you have more than one CommandLineRunner interface implementation class, you can use annotations @Order to specify the order in which all implementation classes are run.

With the help of this series of APIs, Spring boot makes the environment much easier to configure.

Http://www.cnblogs.com/whthomas/p/5270917.html

Http://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/index.html

Tomcat
Tomcat is the default container for spring boot, and here are a few common configurations:

    1. # Tomcat maximum number of threads, default is
    2. server.tomcat.max-threads=
    3. # tomcat URI encoding
    4. server.tomcat.uri-encoding=utf-8
    5. # A temporary folder for files such as Tomcat logs, dumps, and so on, default to the system's TMP folder (for example: C:\Users\Shanhy\AppData\Local\Temp)
    6. Server.tomcat.basedir=h:/springboot-tomcat-tmp
    7. # Open the Tomcat access log, and you can set the method for the log format:
    8. #server. tomcat.access-log-enabled=True
    9. #server. tomcat.access-log-pattern=
    10. # Accesslog directory, default in Basedir/logs
    11. #server. tomcat.accesslog.directory=
    12. # log file directory
    13. Logging.path=h:/springboot-tomcat-tmp
    14. # log file name, default is Spring.log
    15. Logging.file=myapp.log

Jetty
If you are going to choose jetty, it is also very simple to exclude the Tomcat dependency in Pom and add the dependency of the jetty container as follows:

<dependencies>  <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId>    <exclusions>      <exclusion>        <groupId>org.springframework.boot</groupId>        <artifactid>spring-boot-starter-tomcat</ artifactid>      </exclusion>    </exclusions>  </dependency>  <dependency>    <groupId>org.springframework.boot</groupId>    <artifactid>spring-boot-starter-jetty </artifactId>  

Packaged
Packaging method:
CMD into the project directory, using the MVN Clean Packages command to package, take my project projects as an example:

E:\SPRING-BOOT-SAMPLE>MVN Clean Package

You can append a parameter -dmaven.test.skip=true (-dskiptests) to skip the test.
The packaged files are stored in the target directory under the project, such as: Spring-boot-sample-0.0.1-snapshot.jar
Spring-boot-sample-0.0.1-snapshot.war If the POM is configured with a war package

Ii. deploy to a Java EE container
    1. Modify the startup class, inherit Springbootservletinitializer , and override the Configure method
public class Springbootsampleapplication extends springbootservletinitializer{    private static final Logger Logger = Loggerfactory.getlogger (springbootsampleapplication.class);    @Override    Configure(Springapplicationbuilder builder) {        return builder.sources ( This.getclass ());}    }
    1. Modify the jar in the Pom file as war
<!--<packaging>jar</packaging>--><packaging>war</packaging>
    1. Modify Pom to exclude Tomcat plugins

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

<exclusions>

<exclusion>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-tomcat</artifactId>

</exclusion>

</exclusions>

</dependency>

    1. Package deployment to a container
      Use the command MVN clean package to deploy to a web container just like a generic Java EE project.
Third, the useProfile- Sensitive Environment

Spring boot can configure profiles to differentiate between different environments and perform different results in "Configuration Files", "Java Code Classes", "Log Configuration"

1. Configuration files
Using configuration files Application.yml and application.properties differ
Take Application.properties as an example to differentiate the environment application-{by file name profile}.properties
Application.properties

App.name=myappserver.port=8080spring.profiles.active=dev

Application-dev.properties
server.port=8081

Application-stg.properties
server.port=8082


Specify the specific configuration to use when starting the program by adding –spring.profiles.active={profile}
For example we perform Java-jar Demo.jar spring.profiles.active=Dev So how will the contents of the above 3 files be applied?
Spring Boot Loads the default configuration file first, and then overwrites the default configuration with the configuration in the specified profile.

spring.profiles.active Specifies the dev environment by default, and if we specify –SPRING.PROFILES.ACTIVE=STG at run time, the STG environment is applied and the final Server.port value is 8082

2. @profile annotations in Java class
The following 2 different classes implement the same interface, @Profile annotations specify the specific environment

Interface Definition public interface SendMessage {    //Send SMS method definition public    void Send ();} Dev Environment Implementation class @component@profile ("Dev") public class Devsendmessage implements SendMessage {    @Override    public void Send () {        System.out.println (">>>>>>>>dev Send () <<<<<<<<" );    }} STG Environment Implementation Class @component@profile ("STG") public class Stgsendmessage implements SendMessage {    @Override    public void Send () {        System.out.println (">>>>>>>>stg Send () <<<<<<<<" );    }} Startup class @springbootapplicationpublic class Profiledemoapplication {    @Value ("${app.name}")    private String Name;    @Autowired    private SendMessage SendMessage;    @PostConstruct public    void init () {        sendmessage.send ();//The corresponding class will be instantiated according to the environment specified by Profile    }}

3, Logback-spring.xml also support the node to support the distinction

<?xml version= "1.0" encoding= "UTF-8"?><configuration> <include    resource= "org/springframework/ Boot/logging/logback/base.xml "/>    <logger name=" Org.springframework.web "level=" INFO "/>    < Springprofile name= "Default" >        <logger name= "org.springboot.sample" level= "TRACE"/>    </ springprofile>    <springprofile name= "Dev" >        <logger name= "org.springboot.sample" level= "DEBUG"/ >    </springProfile>    <springprofile name= "Staging" >        <logger name= " Org.springboot.sample "level=" INFO "/>    </springProfile></configuration>

Again, do not use the Logback.xml file name. Use Logback-spring.xml

Iv. specifying the external configuration file

Some systems, such as information about databases or other third-party accounts, are not configured to be exposed to developers in the project because of security issues.
In this case, when we run the program, we can specify an external configuration file through the parameters.
Taking Demo.jar as an example, the method is as follows:

Java-jar Demo.jar --spring.config.location=/opt/config/application.properties

Where the file name is arbitrarily defined, no fixed requirements.

V. Create an SH script for a Linux application

The following scripts are for reference only, please make adjustments according to your needs
start.sh

--spring.profiles.active=stg >/dev/null 2>&1 &echo $! > Tpid

stop.sh

Tpid= ' Cat Tpid | awk ' {print '} '

Tpid= ' Ps-aef | grep $tpid | awk ' {print $} ' |grep $tpid ' if [ ${tpid}]; then        kill-9 $tpidfi

check.sh

Tpid= ' Cat Tpid | awk ' {print '} ' tpid= ' Ps-aef | grep $tpid | awk ' {print $} ' |grep $tpid ' if [${tpid}]; Then        Echo app is Running.else        Echo app was not running.fi

kill.sh

#!/bin/sh
# Kill-9 ' ps-ef|grep project name |awk ' {print $} '
Kill-9 ' ps-ef|grep Demo|awk ' {print $} '

Http://www.cnblogs.com/duyinqiang/p/5696342.html

Spring Boot Configuration Priority order

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.