Spring Boot property configuration and use (transfer)

Spring Boot property configuration and using

Spring Boot allows you to use the same application code in different environments through external configuration. Simply put, you can inject properties or modify the default configuration through configuration files.

For an introduction to Spring Boot, please see: http://blog.csdn.net/isea533/article/details/50278205

Spring Boot supports a variety of external configuration methods. The priority of
these methods is as follows:

Command line parameters JNDI attributes
from java:comp/env
Java System properties (System.getProperties()) The random.* property value configured by the
operating system environment variable RandomValuePropertySource The application-{profile}.properties outside the jar package or the application.yml (with spring.profile) configuration file The application- inside the jar package {profile}.properties or application.yml (with spring.profile) application.properties or application.yml outside the configuration file jar package or application.yml (without spring.profile) application.properties or application.yml inside the configuration file jar package (without @PropertySource on the @Configuration annotated class with spring.profile) configuration file






Default properties specified by SpringApplication.setDefaultProperties
Command line parameters

Pass parameters by java -jar app.jar --name="Spring" --server.port=9090.

Parameters are passed in the form of --xxx=xxx.

The parameters that can be used can be defined by ourselves or the default parameters in Spring Boot.

Many people may be concerned about how to configure the web port. These are the parameters provided by Spring Boot. Some of the available parameters are as follows:

# LOGGING
logging.path=/var/logs
logging.file=myapp.log
logging.config= # location of config file (default classpath:logback.xml for logback)
logging.level.*= # levels for loggers, eg "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL , OFF)

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080
server.address= # bind to a specific NIC
server.session-timeout= # session timeout in seconds
server.context-parameters.*= # Servlet context init parameters, eg server.context-parameters.a=alpha
server.context-path= # the context path, defaults to '/ '
server.servlet-path= # the servlet path, defaults to '/'
For more common application properties, please browse here.

Note : The command line parameters are after app.jar!

Command line configuration can be disabled via SpringApplication.setAddCommandLineProperties(false).

Java system properties

Note that the Java system properties are located in java -Dname="isea533" -jar app.jar. The properties that can be configured are the same and have different priorities.

For example, java -Dname="isea533" -jar app.jar --name="Spring!" The name value is Spring!

Operating system environment variable. Those who have

configured JAVA_HOME should know this one.

It should be noted here that some OSes may not support the use of this name, such as server.port, which can be configured using SERVER_PORT.

How to match the specific names, see later in this article.



Where random numbers are used in the RandomValuePropertySource system, for example: my.secret

=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.number.less.than. ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
random.int* supports the value parameter and the max parameter. When the max parameter is provided, the value is the minimum value.

The application configuration file (.properties or .yml)

is directly written in the configuration file:

name=Isea533
server.port=8080
The configuration file in .yml format is:

name: Isea533
server:
    port: 8080
When there is a prefix, use . The configuration file in yml format is simpler. For the usage of .yml configuration file, please see here.

Note : When using .yml, there must be a space between the value of the attribute name and the colon. For example, name: Isea533 is correct, and name: Isea533 is wrong.

The location of the property configuration file

Spring will look for application.properties or application.yml from the /config directory under the classpath or the root directory of the classpath.

/config takes precedence over the classpath root directory

@PropertySource

This annotation can specify a specific property configuration file with a lower priority.

SpringApplication.setDefaultProperties

for example:

SpringApplication application = new SpringApplication(Application.class);
Map<String, Object> defaultMap = new HashMap<String, Object>();
defaultMap.put("name", "Isea-Blog");
/ / It can also be the Properties object
application.setDefaultProperties(defaultMap);
application.run(args);
application (use) the attribute
@Value("${xxx}")

This method is the simplest, through the @Value annotation, the property can be value is injected.

@ConfigurationProperties

Spring Boot makes it easy to inject properties into a configuration object. For example:

my.name=Isea533
my.port=8080
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
Corresponding object:

@ConfigurationProperties(prefix="my")
public class Config {
    private String name;
    private Integer port;
    private List<String> servers = new ArrayList<String>();

    public String geName(){
        return this.name;
    }

    public Integer gePort(){
        return this.port;
    }
    public List<String> getServers() {
        return this.servers;
    }
}
Spring Boot will automatically inject properties with prefix="my" prefixed with my.

Spring Boot will automatically convert the type. When using List, you need to pay attention to initializing the List in the configuration!

Spring Boot also supports nested property injection, for example:

name=isea533
jdbc.username=root
jdbc.password=root
...
corresponding configuration class:

@ConfigurationProperties
public class Config {
    private String name;
    private Jdbc jdbc;
    class Jdbc {
        private String username;
        private String password;
        //getter...
    }

    public Integer gePort(){
        return this.port ;
    }
    public Jdbc getJdbc() {
        return this.jdbc;
    }
}
The properties starting with jdbc will be injected into the Jdbc object.

Use @ConfigurationProperties on @Bean methods

eg:

@ConfigurationProperties(prefix = "foo")
@Bean
public FooComponent fooComponent() {
    ...
}
Spring Boot will inject properties starting with foo into the FooComponent object by name matching.

Attribute placeholders
For example :

app.name=MyApp
app.description=${app.name} is a Spring Boot application
can refer to the previously configured attributes in the configuration file (priorities previously configured can be used here).

The default value can also be set by methods such as ${app.name:default name}, and the default property will be used when the referenced property is not found.

Because of the ${} method will be processed by Maven. If you pom inherited spring-boot-starter-parent, Spring Boot has changed the default ${} method of maven-resources-plugins to @ @ method, such as @name@.

If you are introducing Spring Boot, you can modify and use other separators. You can also shorten command parameters

through property placeholders.

For example, to modify the default web port, you need to use the --server.port=9090 method, if you write in the configuration:

server .port=${port:8080}
then the shorter --port=9090 can be used, and the default value of 8080 is used when this parameter is not provided.

Property name matching rules
For example , there are the following configuration objects:

@Component
@ConfigurationProperties(prefix="person")
public class ConnectionSettings {

    private String firstName;

}
The property names that can be used for firstName are as follows:

person.firstName, standard camel case name
person.first-name, split by dotted line (-), it is recommended to use
PERSON_FIRST_NAME in .properties and .yml configuration files, uppercase underscore form, it is recommended to use
property
You can use JSR-303 annotations for validation, for example:

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {

    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters

}
Finally, the
above is the content of Spring Boot property configuration and use. If there are some incomplete places or readers have more questions, you can check Spring Boot's complete documentation or Externalized Configuration.

For more information about Spring Boot, you can continue to follow this blog.

Spring Boot series
Since there are not enough articles in my blog Spring Boot series, I don't plan to create a column for the time being. If there are more articles, I will create a column.

Getting started with

Spring Boot Spring Boot property configuration and using

Spring Boot to integrate MyBatis

Spring Boot static resource processing

Transfer : http://blog.csdn.net/isea533/article/details/50281151

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326688624&siteId=291194637