Spring Boot 2.0 Tutorial-Configuration detailed

Source: Internet
Author: User

Spring Boot can be configured with the properties file, Yaml file, environment variables, and command line parameters. Attribute values can be injected into the application by, @Value annotations, environment or configurationproperties. The configuration is prioritized as follows:

    1. If Devtools is used, the ~/.spring-boot-devtools.properties in the home directory is the main
    2. @ Testpropertysource Annotated test
    3. @SpringBootTest #properties annotations Test
    4. command-line arguments
    5. Properties provided by Spring_application_json (JSON format, obtained from environment variables or system properties)
    6. ServletConfig properties for configuration
    7. Properties of the ServletContext configuration
    8. jndi configuration, (java:comp/env)
    9. Java System Properties, system.getproperties ()
    10. System Environment Variables
    11. randomvaluepropertysource insertion for random.*
    12. Outside the jar package specifies the profile file, such as the specified profile file inside the application-{profile}.properties (YAML)
    13. jar Package
    14. Apply external application.properties
    15. apply internal application.properties
    16. @PropertySource annotations
    17. default Property ( springapplication.setdefaultproperties () ) For example:
import org.springframework.stereotype.*import org.springframework.beans.factory.annotation.*@Componentpublic class MyBean { @Value("${name}") private String name; // ...}

When the application.properties default value for name is provided, the default value can be overridden by providing a command line value when the program is run java -jar app.jar --name="spring" .

Configure random values

RandomValuePropertySourceRandom values can be easily injected into the configuration file. For example

my.secret=${random.value}my.number=${random.int}my.bignumber=${random.long}my.uuid=${random.uuid}my.number.less.than.ten=${random.int(10)}my.number.in.range=${random.int[1024,65536]}
Access Command Sweat parameters

By default, Springapplication converts the command-line arguments to property and adds them to Environment the. As mentioned earlier, command-line parameters overwrite other configurations. If you do not want the command line arguments to be added to Environment , you can set by calling SpringApplication.setAddCommandLineProperties(fals) .

Application configuration file

SpringApplicationLoad the application.properties file, add its variables to the Environment , find location: 1. Directory of the current directory /config 2. Subdirectories under current directory 3. Classpath config 4. classpath directory If you do not want to use the application.properties file can use spring.config.name Specify the configuration name, also by spring.config.location specifying the location of the configuration file

java -jar myproject.jar --spring.config.name=myprojectjava -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

If you spring.config.location are using a directory, it should end with the / spring.confing.name name appended to the later lookup configuration file.

Specify the configuration file

In addition to application.properties files, you can application-{profile}.properties name the specified configuration file in the same form. EnvironmentThere is a default configuration, (default), which is used if no other profile is activated application-default.properties . If more than one specified configuration file is available, select the most recent configuration file.

Placeholder for configuration file

application.propertiesCan be used in subsequent configurations, such as

app.name=MyAppapp.description=${app.name} is a Spring Boot application
Using YAML configuration Files

When Snakeyaml is added, springapplication can support YAML configuration, and adding spring-boot-starter automatically adds a dependency on Snakeyaml.

Loading Yaml

SpringApplicationThere are two ways to load a yaml configuration file, 1. Use to load Yaml YamlPropertiesFactoryBean as Properties , 2. Use to YamlMapFactoryBean load Yaml as a map. The following YAML configuration files:

environments:dev:url: http://dev.example.comname: Developer Setupprod:url: http://another.example.comname: My Cool App

The above configuration file is equivalent to the properties configuration

environments.dev.url=http://dev.example.comenvironments.dev.name=Developer Setupenvironments.prod.url=http://another.example.comenvironments.prod.name=My Cool App

The Yaml list adds an ordinal (index) By default, for example:

my:servers:- dev.example.com- another.example.com

The equivalent properties are configured to

my.servers[0]=dev.example.commy.servers[1]=another.example.com

You can @ConfigurationProperties bind an attribute to a variable by using annotations, for example:

@ConfigurationProperties(prefix="my")public class Config {private List<String> servers = new ArrayList<String>();public List<String> getServers() {return this.servers;}}
Multiple YAML configuration files

spring.profilesmultiple YAML profiles can be specified as keys in a single file. For example:

192.168.1.100---spring:profiles: developmentserver:address: 127.0.0.1---spring:profiles: productionserver:address: 192.168.1.120

As indicated in the above file, if the development configuration is active, the server.address is set to 127.0.0.1. Similarly, if the production configuration is active then the server.address is configured to 192.168.1.120. If both development and production are not enabled, the default setting of Server.address is set to 192.168.1.100 if no activation is specified, then default configuration is used, such as the following example, spring.security.user.password Use only if you do not specify an activation configuration

server:  8000---spring:  profiles: default  security:    user:      password: weak

The following example password will be set because he does not belong to any one of the configurations:

server:  8000spring:  security:    user:      password: weak
Injecting values with @configurationproperties

Using @value () is a hassle when injecting values from multiple properties, and Spring boot can use @configurationproperties for simplified configuration, such as:

Package com.example;Import java.net.InetAddress;Import java.util.ArrayList;Import java.util.Collections;Import java.util.List;Import org.springframework.boot.context.properties.ConfigurationProperties;@ConfigurationProperties ("Acme")PublicClassacmeproperties {PrivateBoolean enabled;Private InetAddress remoteaddress;PrivateFinal Security Security =New Security ();PublicBooleanIsEnabled() { ... }PublicvoidSetEnabled(Boolean enabled) {...}Public inetaddressGetremoteaddress() { ... }PublicvoidSetremoteaddress(InetAddress remoteaddress) { ... }Public SecurityGetsecurity() { ... }PublicStaticClassSecurity {Private String username;private String password;Private list<string> roles =New Arraylist<> (Collections.singleton ("USER"));Public StringGetUserName() { ... }public void setusername(String username) {...} Public String GetPassword() {...} public void setpassword(String password) {...} Public list<string> getroles() {...} Public  void setroles(list<string> roles) {...}       }} 

Its properties are defined as follows

acme.enable=falseacme.remote-address=192.168.1.1acme.security.username=usernameacme.security.password=passwordacme.security.roles=roles1,roles2

Need to be in the configuration of @configuration

@Configuration@EnableConfigurationProperties(AcmeProperties.class)public class MyConfiguration {}

Of course if the Acmeproperties class is a bean then there is no need to configure specifying @EnableConfigurationProperties(AcmeProperties.class) for example:

@Component@ConfigurationProperties(prefix="acme")public class AcmeProperties {// ... see the preceding example}

The equivalent YAML configuration file

192.168.1.1security:username: adminroles:  - USER  - ADMIN
Untie rules

The @configurationproperties binding variable is very flexible, for example:

@ConfigurationProperties(prefix="acme.my-project.person")public class OwnerProperties {private String firstName;public String getFirstName() {return this.firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}}

Can be successfully bound for the following ways

    • Acme.my-porject.person.first-name
    • Acme.my-project.person.first_name
    • Acme.my-project.person.firstname
    • Acme_myproject_person_firstname
@ConfigurationProperties Checksum

The @ConfigurationProperties supports JSR-303 javax.validation annotations, such as

@ConfigurationProperties(prefix="acme")@Validatedpublic class AcmeProperties {@NotNullprivate InetAddress remoteAddress;// ... getters and setters}
The difference between @ConfigurationProperties and @value
function @configurationProperties @Value
Untie rules Y N
Meta Data support Y N
Spel N Y
Profiles

Spring profile can divide the application's configuration into multiple parts, only in the specified environment. Any @component or @configutaion can use @profile to restrict its loading, for example

@Configuration@Profile("production")public class ProductionConfiguration {// ...}

You can use spring.profiles.active the Environment variable settings to activate which profile. For example, setting in Application.properties

spring.profiles.active=dev,hsqldb

or use the command line

java -jar app.jar --spring.profiles.active=dev,hsqldb
Original link: https://www.codemore.top/cates/Backend/post/2018-05-20/spring-boot-configuration/

Spring Boot 2.0 Tutorial-Configuration detailed

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.