SpringBoot entry to the master :( c) profile

Here Insert Picture Description

Foreword

Spring Boot using the "habit over configuration" (configuration exists a large number of projects, in addition to built-in configuration of a habit, so you do not need to manually configure) concept to get your project up and running quickly. But if some configuration does not meet our requirements how to do it, which you need to know Spring Boot configuration files.

text

The default configuration file

SpringBoot use a global configuration file, configuration file support properties and yml two types of configuration, the configuration file name is fixed application.properties/application.yml, the role of Sping Boot global configuration file is the default configuration for some configuration values to be modified.

Priority profile

springboot started, it scans the following location of application.properties/application.ymlthe file as Spring boot default configuration file

  • -file: ./ config / (project config folder)

  • -file: ./ (directly into the project path)

  • -classpath: / config / (config file folder classpath)

  • -classpath: / (directly into the class path)

In the end of a high priority, a high priority configuration overwrites the low priority configuration;

SpringBoot will be loaded from the four positions of all main configuration file; complementary configuration ;

Profiles placeholder

1, a random number

Profile $ {random} may be used to generate a variety of different types of random values, thereby simplifying the trouble code generation, such as generating an int, long string value or string.

randomtest:
  value: ${random.value}
  int: ${random.int}
  intarr: ${random.int(10)}
  long: ${random.long}
  longstr: ${random.long(10)}
  uuid: ${random.uuid}

2, the configuration of the placeholder value acquired previously, if no specified default value s

user: 
	user-name: 张三${random.uuid}
	age: ${random.int}
	birth: 2017/12/15	
	dog: 
		name=${user.hello:hello}_dog  //如果有user.hello,使用前面配置的user.hello的值,没有则使用默认值hello
		age=15

Use custom configuration file

Sometimes we do not want to put all configurations application.properties inside, then we can use @PropertySourceannotations to load the specified configuration file
we can customize a configuration file, for example user.properties, also on a path with the src / main / resources below.
We can use in the configuration class @PropertySourceto load the specified comment user.propertiesProfile

@PropertySource(value = {"classpath:user.properties"})
@ConfigurationProperties(prefix = "user")
@Component
@Data
public class User {

    private String userName;
    private int age;
    private Date birthday;

}

Note: @PropertySourceAnnotations are not supported yml profile

External Configuration - Command line parameters

Spring Boot jar package is based on the run, labeled jar package can be run directly by the following command:

java -jar xx.jar

The following command can modify the tomcat port number:

java -jar xx.jar --server.port=8081

As can be seen, the command line minus two consecutive - application.properties attribute value is identified in the assignment.
Therefore java -jar xx.jar --server.port = 8081 is equivalent to add attributes in the configuration file server.port = 8081.
If you are afraid of the command line at risk, you can use SpringApplication.setAddCommandLineProperties (false) to disable it.

In fact, there are a variety of ways provided Spring Boot application, Spring Boot obtained from multiple sources attribute properties include the following:

  1. Command-line arguments, all of the configurations can be specified on the command line, a plurality of configuration separated by spaces; - = CI value

    java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087  --server.context-path=/abc
    
  2. JNDI properties comp / env: From java

  3. Java system properties (System.getProperties ())

  4. Operating system environment variables

  5. random RandomValuePropertySource configuration. * Property Value

    Looking for outgoing packets within a jar jar package;

    Priority loaded with profile

  6. jar outer package or application- {profile} .properties application.yml (with spring.profile) profile

  7. Internal jar package application- {profile} .properties or application.yml (with spring.profile) Profile **

    Again without loading profile

  8. jar or outer package application.properties application.yml (without spring.profile) profile

  9. Internal jar package application.properties or application.yml (without spring.profile) profile

  10. @PropertySource class notes on @Configuration

  11. By SpringApplication.setDefaultProperties specified default property

All supported configurations load source; refer to the official documentation

Profile value acquisition

SpringBoot There are two ways to get the value of the configuration file

Use @Value comment

Profiles provide support for custom attributes, so that we can put some constants in the configuration here:

user:
  user-name: 张三
  age: 18
  birthday: 2000/01/01

Then directly be used in place through annotations @Value(value=”${config.name}”)can be bound to a property on top of what you want

@Component
@Data
public class User{

    @Value("${user.user-name}")
    private String userName;
    @Value("${user.age}")
    private int age;
    @Value("${user.birthday}")
    private Date birthday;

}

Test run, the output of the acquired user

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {
    @Autowired
    User user;
    @Test
    public void contextLoads() {
        System.out.println(user);
    }
}

The output results are as follows

User (userName = John Doe, age = 18, birthday = Sat Jan 01 00:00:00 CST 2000)

Use @ConfigurationProperties comment

Sometimes attribute too much, one is bound to the field on the property too tired, we can use the @ConfigurationPropertiesannotation
meaning of the notes is the value of each property's configuration file is mapped to the component, its properties prefix = " xxx "specified configuration file all of the properties which were below one mapping
Note: this component is only a container of components, in order to provide a container @ConfigurationPropertiesfunction; it must have the class @Componentnotes
so that we do not have to configure each property in the @Valuenotes only needs to be configured on the class @ConfigurationProperties(prefix = "user")
SpringBoot automatically mapped on each attribute value corresponding to the configuration file

@Component
@ConfigurationProperties(prefix = "user")
@Data
public class User{

    private String userName;

    private int age;

    private Date birthday;

}

Test run, the output of the acquired user

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {
    @Autowired
    User user;
    @Test
    public void contextLoads() {
        System.out.println(user);
    }
}

The output results are as follows

User (userName = John Doe, age = 18, birthday = Sat Jan 01 00:00:00 CST 2000)

@ConfigurationProperties difference @Value and annotations

@ConfigurationProperties @Value
Batch Configuration stand by not support
Loosely bound (loose syntax) stand by not support
Game not support stand by
JSR303 data check stand by not support
Complex type package stand by not support
  1. Bulk configuration: As indicated above example, @ConfigurationPropertiesmay be injected into a batch configuration file attributes, @Valueonly one injection a
  2. Loose Syntax: @ConfigurationPropertiessupport loose syntax, such as the configuration file using the user-name @ConfigurationPropertiescan give injection userName attribute value, but @Value("${user.userName}")can not assign user-name attribute in the configuration file to a userName
  3. SpEL language: @valuesupport SpEL language, such as:
    @Value("#{11*2}")
    private int age;
    
    However, if the age = # {11 * 2} , the profile @ConfigurationPropertiesis not possible to calculate the value of the injection to the age property
  4. JSR303 validation: Use @ConfigurationPropertiescan check data, such as:
    @Email
    private String email;
    
  5. @ConfigurationPropertiesSupport complex encapsulant, such as
    user:
      user-name: 张三
      age: 18
      birthday: 2000/01/01
      map: {1:v1,k2:v2}
    
    @Component
    @ConfigurationProperties(prefix = "user")
    @Data
    public class User{
    
        private String userName;
    
        private int age;
    
        private Map map;
    
    }
    
    @ConfigurationPropertiesThe configuration file can be directly assigned to map attributes of map

Profile- multi-environment configuration

When an application needs to be deployed to different operating environment, configuration usually will be different, the simplest such as logging, production logging will log level WARN or higher level, and the log written to the log file, and the development time log level required for the output to the console to DEBUG, log. If every time you replace the release profile, this is too much trouble, Spring Boot's Profile gave us two solutions, to get command with parameters.

1, multi-file Profile

We in the preparation of the master configuration file, the file name can be application- {profile} .properties / yml
default application.propertiesconfiguration can be used in the configuration file spring.profiles.active= xxxto specify which profile to use
for example we want to use application-dev.ymlthis configuration file can be configured in the main configuration file

spring:
  profiles:
    active: dev

2, yml support multiple block the way

yml may be used ---to separate code blocks, which can be specified using code blocks

server:
  port: 8081
spring:
  profiles:
    active: prod
---
server:
  port: 8083
spring:
  profiles: dev

---
server:
  port: 8084
spring:
  profiles: prod  #指定属于哪个环境

You can also use an external activation parameters which profile to use

java -jar spring-boot.jar --spring.profiles.active=dev;

Or use virtual machine parameters

-Dspring.profiles.active=dev
Published 40 original articles · won praise 9 · views 20000 +

Guess you like

Origin blog.csdn.net/aawmx123/article/details/102555745