Spring Boot Configuration Priority order

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

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 fromapplication.properties. In fact, aresourcefile read from the directoryapplication.propertiesis 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 to converting command-line arguments starting with "--" to configuration parameters that can be used in the app, such as "--name=alex", which sets the value of the configuration parameter "name" 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(100)}
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
@EnableAutoConfiguration
public 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: development
db:
 url: jdbc:hsqldb:file:testdb
 username: sa
 password:
---
spring:
 profiles: test
db:
 url: jdbc: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, Iapplication.propertieswrite the configuration of the local MySQL in the directory:









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

During the commissioning phase of your project, the project will always use the local MySQL database. And once packaged, declare one externallytest_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.


public class 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
    // ..... 
    
}


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


public class ApplicationConfigure implements CommandLineRunner  {

    @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
    // ..... 
    @Override
    public void run(String... strings) throws Exception {
        // Some methods, classes, and properties are preloaded.
    }
}


If you have more than oneCommandLineRunnerinterface implementation class, you can use annotations@Orderto 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:

[Java]

    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>
  </dependency>
<dependencies> 


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


Second. 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
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(this.getClass());
    }

}

2.Modify the jar in the Pom file as war

<!-- <packaging>jar</packaging> -->
<packaging>war</packaging>

3.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>


4.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 use Profile Differentiate the 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, distinguish environment application-{profile }.properties by file name
Application.properties


app.name=MyApp
server.port=8080
spring.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()<<<<<<<<<");
     }
}
// start class
@SpringBootApplication
Public class ProfiledemoApplication {
     @Value("${app.name}")
     Private String name;
     @Autowired
     Private SendMessage sendMessage;
     @PostConstruct
     Public void init(){
         sendMessage.send();// will instantiate the corresponding class according to the environment specified by the 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


Fourth. 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.



Fifth. Create an SH script for a Linux application


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



#!/bin/sh
rm -f tpid
nohup java -jar /data/app/myapp.jar --spring.profiles.active=stg > /dev/null 2>&1 &
echo $! > tpid


stop.sh

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


tpid=`ps -aef | grep $tpid | awk ‘{print $2}‘ |grep $tpid`
if [ ${tpid} ]; then
        kill -9 $tpid
fi


check.sh


tpid=`cat tpid | awk ‘{print $1}‘`
tpid=`ps -aef | grep $tpid | awk ‘{print $2}‘ |grep $tpid`
if [ ${tpid} ]; then
        echo App is running.
else
        echo App is 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

Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

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.