Spring Boot 2.0.0 Reference Manual _ Chinese version _part iv_24

Source: Internet
Author: User
Tags arrays bind constructor json naming convention static class uuid valid

Article Author: Tyan
Blog: noahsnail.com |  CSDN | Jane Book 24. External configuration

Spring boot allows you to perform an externalized configuration, so you can run the same application code in different environments. You can use attribute files, YAML files, environment variables, and command-line parameters for external configuration. Attribute values can be injected directly into your beans using the @value annotation, accessed through the environment abstraction of spring or binding to a structured object via @configurationproperties.

Spring Boot uses a very special propertysource sequence, which is designed to allow for reasonable rewriting of values. Attributes are considered to be in the following order: the Development Tools global setting properties under the root directory (~/.spring-boot-devtools.properties when the development tool is activated). @testpropertysource annotations in the test. The @springboottest#properties annotation attribute in the test. Command line arguments. Attributes in Spring_application_json (inline JSON embedding in environment variables or system properties). ServletConfig initialization parameters. ServletContext initialization parameters. The Jndi attribute of the java:comp/env. Java System Properties (System.getproperties ()). Operating system environment variables. Randomvaluepropertysource only have attributes in random.*. The application properties (Application-{profile}.properties and YAML variables) of the specified configuration file outside the jar package. The application properties (Application-{profile}.properties and YAML variables) of the specified configuration file within the jar package. Application properties (Application.properties and YAML variables) outside the JAR package. Application properties within the jar package (application.properties and YAML variables). The @propertysource annotation in the @Configuration class. Default properties (specified by Springapplication.setdefaultproperties).

To provide a concrete example, suppose you developed a @component using the name attribute:

Import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*

@Component Public
class Mybean {

    @Value ("${name}")
    private String name;

    // ...

}

In your application path (for example, inside your jar), you can use application.properties to provide a reasonable default property value for name. When running in a new environment, application.properties can be provided outside the jar to override name, and for a one-time test you can start by specifying a command-line switch (for example, Java-jar app.jar--name= "Spring").

Spring_application_json can be provided on the command line through environment variables. For example, in the Unix shell:

$ Spring_application_json= ' {' foo ': {' bar ': ' Spam '} ' Java-jar Myapp.jar

In this example, there will be foo.bar=spam in spring's environment. You can also provide JSON as a spring.application.json in system variables.

$ Java-dspring.application.json= ' {' foo ': ' Bar '} '-jar Myapp.jar

or command line arguments:

$ Java-jar Myapp.jar--spring.application.json= ' {' foo ': ' Bar '} '

or Jndi variable Java:comp/env/spring.application.json 24.1 configuration random value

Randomvaluepropertysource is useful when injecting random values (for example, injecting a secret or test case). It can produce integers,longs,uuids or strings, 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 (Ten)}
my.number.in.range=${random.int[1024,65536]}

random.int* syntax OPEN value (, max) Close,open,close can be any character, Value,max is an integer. If Max is provided, value is the minimum and Max is the maximum (not included). 24.2 Access Command line Properties

By default, Springapplication converts any command-line arguments (beginning, for example,--server.port=9000) to a property and adds them to spring's environment. As mentioned earlier, command line properties always take precedence over other configuration sources.

If you want to add a command-line attribute to environment, you can disable it using Springapplication.setaddcommandlineproperties (false). 24.3 Application properties File

Springapplication loads the properties from the Application.properties file in the following location and adds them to spring's environment:

Subdirectories of the current directory/config

Current directory

The/config package in Classpath

root directory of Classpath

This list is sorted by priority (attributes in a higher position override those defined at a lower position).

You can also use the Yaml (. yml) file to replace the. properties file.

If you do not like using application.properties as the name of the configuration file, you can change the name of the configuration file by specifying the Spring.config.name environment attribute. You can also use the Spring.config.location environment attribute to refer to an explicit location (where the directory location or file path is separated by commas).

$ Java-jar Myproject.jar--spring.config.name=myproject

Or

$ Java-jar Myproject.jar--spring.config.location=classpath:/default.properties,classpath:/override.properties

Spring.config.name and spring.config.location can be used early in deciding which file to load, so they must be defined as ambient attributes (typically the operating system environment, System properties, or command-line arguments).

If the spring.config.location contains directories (as opposed to files), they should be in/at the end (before loading, add the name from Spring.config.name, including the name of the specified profile). The file specified in Spring.config.location is used as is, and the specified profile variable is not supported, and will be overwritten by the properties of any specified profile.

The default search path is always classpath:,classpath:/config,file:,file:config/, regardless of the value in Spring.config.location. Search paths are sorted from lowest to highest (file:config/). If you specify your own location, they take precedence over all default locations and use the same order from lowest to highest. This allows you to set the default value for your application in application.properties (or you can select the base name of the other generated file for spring.config.name), overwrite it with other files at run time, and leave the default values.

If you use an environment variable instead of a system attribute, most operating systems do not allow a period-delimited keyword, but you can use an underscore instead (for example, Spring_config_name instead of spring.config.name).

If you are running in a container, the Jndi attribute (in java:comp/env) or servlet context initialization parameters can also be used in place of environment variables or system attributes. 24.4 specific profile properties

In addition to application.properties files, specific profile properties can be defined using the naming convention application-{profile}.properties. Environment has a series of default profiles (default is [defaults]), and if no active profile is set, the default configuration file is used (for example, if an explicit profile is not activated, The properties in the Application-default.properties are loaded).

The specific profile attributes are loaded application.properties from the same location, and the specific profiles always overwrite the neutral configuration file, regardless of whether the specific profile is inside or outside of the jar you are packing.

If you specify several configuration files, the last one will be applied. For example, the configuration file specified by the Spring.profiles.active property is added after those configured files through the Springapplication API, so the priority is higher.

If you specify any files in the spring.config.location, the specific profile version of those files will not be considered. If you also want to use a specific profile attribute, use the table of contents in Spring.config.location. 24.5 placeholders in Properties

When the values in Application.properties are used, they are filtered through the existing environment, so you can refer to the values defined above (for example, from the System properties).

App.name=myapp
App.description=${app.name} is a Spring Boot application

You can also use this technique to create a short version of the existing spring boot properties. For more details on how to use it, see section 70.4, "Using ' short ' command line arguments." 24.6 Use Yaml instead of properties

Yaml is a superset of JSON that can be used to specify hierarchical configuration data in a very convenient form. When your classpath has Snakeyaml libraries, the Springapplication class automatically supports YAML as a substitute for properties.

If you use ' starters ', Snakeyaml will be provided automatically by Spring-boot-starter. 24.6.1 Loading Yaml

The spring Framework provides two classes to facilitate loading of YAML documents. Yamlpropertiesfactorybean will load Yaml as Properties,yamlmapfactorybean to load Yaml as a map.

For example, the following YAML document:

Environments:
    Dev:
        url:http://dev.bar.com
        name:developer Setup
    prod:
        url:http://foo.bar.com
        Name:my Cool APP

will be converted to these properties:

environments.dev.url=http://dev.bar.com
environments.dev.name=developer Setup
environments.prod.url= http://foo.bar.com
environments.prod.name=my Cool App

The Yaml list refers to the key represented as an attribute through the [index] solution, such as this yaml:

my:
   servers:
       -dev.bar.com
       -foo.bar.com

will be converted to these properties:

My.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

To bind these properties like the DataBinder of spring (@ConfigurationProperties function), You need to have attributes in a target bean of type java.util.List (or set), you need to provide a setter or initialize it with a variable value, for example, to bind the attribute value above:

@ConfigurationProperties (prefix= "i") public
class Config {

    private list<string> servers = new ArrayList <String> ();

    Public list<string> Getservers () {return
        this.servers;
    }
}
24.6.2 exposes Yaml as attribute in spring environment

The Yamlpropertysourceloader class can be yaml as Propertysource in spring's environment. This allows you to access the Yaml property using familiar @value annotations and placeholder syntax. 24.6. More than 3 profile YAML documents

You can specify multiple profile-specific YAML documents in a single file, and when writing files, use the Spring.profiles keyword to indicate which document is used. For example:

Server:
    address:192.168.1.100
---
spring:
    profiles:development
Server: Address
    : 127.0.0.1
---
spring:
    profiles:production
server:
    address:192.168.1.120

In the above example, if the development profile is activated, the server.address value is 127.0.0.1. If the development and production profiles are not available, the server.address value is 192.168.1.100.

When the application context is started, the default profile is activated if no explicit activation profiles are active. So in this Yaml file we only set the Security.user.password in the "Default" profile.

Server:
  port:8000
---
spring:
  profiles:default security
:
  User:
    password:weak

In this example, the password is always set because it is not added to the profile, and when necessary we must explicitly reset it in the other profile:

Server:
  port:8000 security
:
  User:
    password:weak

Spring Profiles is designed to use the "spring.profiles" element to selectively negate with the! character. If the negative and non negative profile points to a single document, it must match at least one non-negative profile, possibly without a negative profile. 24.6.4 Yaml Disadvantage

The Yaml file cannot be loaded by @propertysource annotations. So in this case if you need to load the value, you need to use the property file. 24.6.5 Merge Yaml list

As we have seen above, any YAML content will eventually be converted to attributes. This process may be counterintuitive when overriding the "List" property through profile.

For example, assume that the name and description properties of the Mypojo object are empty by default. Use a Mypojo list from fooproperties:

@ConfigurationProperties ("foo") public
class Fooproperties {

    private final list<mypojo> List = new Arraylist<> ();

    Public list<mypojo> GetList () {return
        this.list;
    }

}

Consider the following configuration:

Foo:
  list:
    -name:my name
      description:my description
---
spring:
  profiles:dev
foo:
  list:
    -Name:my another name

If the dev profile is not activated, Fooproperties.list will contain a mypojo input defined above. However, if Dev profile is available, lists still contains only one input (name is "My another name" and description is empty). This configuration will not be able to add a second Mypojo to the list, and it will not be able to merge the items.

When you specify a collection in multiple profiles, the highest priority collection is used (which is the only one):

Foo:
  list:
    -name:my name
      description:my description
    -name:another name
      Description: Another description
---
spring:
  profiles:dev
foo:
  list:
     -Name:my another name

In the above example, assuming that the dev profile is activated, Fooproperties.list will contain a Mypojo input (name "My another name" and description empty). 24.7 Type-Safe configuration Properties

Boot provides an alternative way to handle attributes, allowing strongly typed beans to manage and verify the configuration of your application. For example:

@ConfigurationProperties (prefix= "Connection") public
class ConnectionProperties {

    private String username;

    Private inetaddress remoteaddress;

    ... getters and setters

}

It is recommended that you add getters and setters, which are based on the standard Java Beans Property descriptor, as in spring MVC. They are mandatory for mutable types or for those types that can be cast directly from string. As long as they are initialized, maps, collections or arrays require getter methods, but no setter methods are required because they can be directly changed by binding them. If you have a setter, you can create maps, collections, and arrays. Maps and collections can be extended through getter, and array extensions require setters. If they have a default constructor, or the constructor receives a value that can be cast from a string type, the embedded Pojo property can also be created (so the setter is not mandatory). Some people use the Lombok project to automatically add getter and setter.

Please see the difference between @value and @configurationproperties.

You also need to list the attribute classes to register in the @enableconfigurationproperties Note:

@Configuration
@EnableConfigurationProperties (connectionproperties.class) public
class Myconfiguration {
}

When @configurationproperties is registered in that way, the bean will have a regular name:<prefix>-<fqn>,<prefix> is the prefix of the environment keyword specified in the @configurationproperties note,<fqn> is the full qualified name of the bean. If the annotation does not provide any prefixes, only the full qualified name of the bean is used.

In the example above, the bean name is connection-com.example.connectionproperties, assuming the connectionproperties is in the Com.example package.

Even if the above configuration creates a regular bean for connectionproperties, we recommend that @configurationproperties only handle the environment, especially not to inject additional beans from the context. As has been said, for any bean with @configurationproperties annotations can be configured according to the environment attribute, @EnableConfigurationProperties annotations are automatically applied to your project. Make sure ConnectionProperties is already a bean and you can abbreviate the above myconfiguration:

@Component
@ConfigurationProperties (prefix= "Connection") public
class ConnectionProperties {

    //... Getters and Setters

}

This style of configuration works particularly well in Springapplication's externalized YAML configuration:

# application.yml

Connection:
    username:admin
    remoteaddress:192.168.1.1

# Additional configuration As required

To work with @configurationproperties beans, you can inject them in the same way as any other bean:

@Service public
class MyService {

    private final connectionproperties connection;

    @Autowired public
    MyService (connectionproperties connection) {
        this.connection = connection;
    }

     //...

    @PostConstruct public
    void OpenConnection () {
        Server server = new server ();
        This.connection.configure (server);
    }

Using @configurationproperties also allows you to generate metadata files that Ides can use. For more details, see Appendix B, Configuring the Meta data Appendix. 24.7.1 Third-party configuration

You can also use @configurationproperties to annotate a class, or you can use it on a public @bean method. This is especially useful when you want to bind attributes to third party components outside of your control.

@ConfigurationProperties (prefix = "foo")
@Bean public
foocomponent foocomponent () {
    ...
}

Any attribute defined with the Foo prefix will be mapped to the foocomponent bean in a manner similar to the connectionproperties example above. 24.7.2 loosely bound

Spring boot uses loose rules to bind the Environment property to the @configurationproperties beans, so you do not need to match the Environment property name to the Bean property name. Common useful examples include dash dividers (for example, Context-path binding to ContextPath), case (for example, port binding to port,) environment properties.

For example, given the following @configurationproperties class:

@ConfigurationProperties (prefix= "person") public
class Ownerproperties {

    private String firstName;

    Public String Getfirstname () {return
        this.firstname;
    }

    public void Setfirstname (String firstName) {
        this.firstname = firstName;
    }

}

The following property names can be used:

table 24.1. Loose binding

Property Note
Person.firstname Standard hump notation
Person.first-name Dash annotation, recommended for use in. Properties and. yml files
Person.first_name Underline annotations,. Alternative notation in properties and. yml files
Person_first_name Uppercase form. Recommended when using System variables
24.7.3 Property Conversion

When the spring bound property is @configurationproperties beans, it attempts to cast the external application property to the correct type. If you need to customize the type conversion you can provide a conversionservice bean (Bean ID is conversionservice), or custom property editor (via Customeditorconfigurer Bean), or custom converters (a bean definition with @configurationpropertiesbinding annotations).

The bean requires early in the application lifecycle to ensure that the dependencies that Conversionservice uses are limited. In general, any dependencies you require may not be fully initialized at the time of creation. If your custom conversionservice does not require you to configure keyword casts, you may want to rename your custom Conversionservice, and relies only on custom converters that satisfy @configurationpropertiesbindings. 24.7.4 @ConfigurationProperties Verification

Spring boot attempts to validate the externalized configuration by using JSR-303 (if it is in Classpath) by default. You can simply add the JSR-303 javax.validation constraint annotation to your @configurationproperties class:

@ConfigurationProperties (prefix= "Connection") public
class ConnectionProperties {

    @NotNull
    private InetAddress remoteaddress;

    ... getters and setters

}

To verify an embedded property value, you must annotate the associated field as a @valid to trigger its checksum. For example, build on the connectionproperties example above:

@ConfigurationProperties (prefix= "Connection") public
class ConnectionProperties {

    @NotNull
    @Valid
    private remoteaddress remoteaddress;

    Getters and setters public

    static class Remoteaddress {@NotEmpty a public
        String hostname;

        ... getters and setters

    }

}

By creating a bean definition called configurationpropertiesvalidator, you can also add custom spring Validator. @Bean method should declare static. The Configuration property Validator is created early in the application lifecycle, declaring that the @bean method is a static method, allowing the bean to be created without instantiating the @configuration class. This avoids any problems that might arise from any early instantiation. Here's an example of a property validation so you can see how to set it up.

The Spring-boot-actuator module contains an endpoint that exposes all the @configurationproperties beans. Simply point your web browser to/configprops or use the equivalent JMX endpoint. For more details, see Product-level features 24.7.5 @ConfigurationProperties and @value

@Value is a core container feature that does not provide the same functionality as a type-safe configuration property. The following table summarizes the features supported by @configurationproperties and @value:

function @ConfigurationProperties @Value
Loosely bound Yes No
Meta-data support Yes No
Spel Assessment No Yes

If you have defined some configuration keywords for your component, we recommend that you group them into a pojo with @configurationproperties annotations. Also note that @value does not support loose binding, and it is not a good choice if you need to provide a value with an environment variable.

Finally, although you can write an expression in @value, this expression cannot be processed from the application properties file.

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.