preface

If you have used Spring Boot, you know that its configuration parameters are essential, such as MySql connection, port number configuration, etc., all need Spring Boot config parameter configuration. Let’s have a look at some commonly used configurations in our work and development, and the way to obtain configuration parameters.

One or two configuration files

Bootstrap (.yml or.properties) and Application (.yml or.properties).

1. Differences in loading sequence

Yml (bootstrap.properties) is loaded first, and application.yml (application.properties) is loaded later.

2. Application scenarios

2.1 Both bootstrap.yml and application.yml can be used to configure parameters.

2.2 Bootstrap. yml can be understood as the configuration of some parameters at the system level, which generally do not change.

2.3 Applicationn. yML can be used to define application-level, mainly for automatic configuration of Spring Boot projects.

The bootstrap configuration file can be used in the following scenarios.

When you use Spring Cloud Config to configure the configuration center, you need to add the configuration properties connected to the configuration center in the bootstrap configuration file to load the configuration information of the external configuration center.

Some fixed attributes that cannot be overridden some encryption/decryption scenarios;

2. Configuration files for different environments

In the work, often encounter a lot of different environments, such as the development of the local database, online use of another set of database, online environment is another set of database, each time to change the port, especially tedious, how to do? Configure different files for different environments.

Spring.profiles. active uses this property to specify which profiles are active.Copy the code

Switch to different environments, using different port numbers:

3. Read configuration file information

The @value annotation reads the file

For example, we define two parameters: name = DT age=24

The @Configuration annotation is essentially @Component. By definition, the @Configuration annotation is still @Component. A later article will explain the difference between the two primary keys.

@Configuration
public class ConfigParamsConfiguration {

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

    @Value("${dt.age}")
    private Integer age;

    public String getConfig(a) {
        return name+"/"+age; }}Copy the code

Interface test:

@RestController
@RequestMapping("api/test")
public class ConfigController {

    @Autowired
    private ConfigParamsConfiguration configParamsConfiguration;

    @GetMapping("/getParams")
    public String getConfig(a){
        returnconfigParamsConfiguration.getConfig(); }}Copy the code

2, Environment read the file

Create a new config.yml file and configure the same as above:

Read config. Yml from Environment instance:

@Configuration
@PropertySource(value = {"classpath:config.yml"})
public class EnvironmentParamsConfiguration {

    @Autowired
    private Environment environment;

    public String getConfig(a){
        String name = environment.getProperty("dt.name");
        String age = environment.getProperty("dt.age");
        return name+"/"+age; }}Copy the code
@PropertySource(value = {"classpath:config.yml"})  // Config file address
Copy the code

Testing:

 @Autowired
 private EnvironmentParamsConfiguration environmentParamsConfiguration;
 
 @GetMapping("/getEnvParams")
 public String getEnvParams(a){
     return environmentParamsConfiguration.getConfig();
 }
Copy the code

ConfigurationProperties reads the configuration file

Adding @values one by one becomes a bit more cumbersome when you have a large number of arguments, but Spring provides another way.

oauth:
  clientId: qq_41107231
  clientSecret: secret
  redirectUri: https://blog.csdn.net/qq_41107231
  grantType: code
Copy the code

Read the contents of the file with the @configurationProperties instance:

@Data
@Component
@ConfigurationProperties(prefix = "oauth")
public class ConfigurationPropertiesParamsConfiguration {

    private String clientId;

    private String clientSecret;

    private String redirectUri;

    private String grantType;

}
Copy the code

The @configurationProperties attribute can be prefixed and will default to looking for the specified variable in application.*. 2. @data must be added because it automatically helps add the default setter method to the property and then get the variable through the getter method.

Can our variables be read if they are underlined or underlined?

It can still be read, and the configuration is flexible.

In addition, @ConfigurationProperties can be used with validation annotations to avoid unnecessary errors in the development environment. Add the Validation dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Copy the code

We have misconfigured the variables in the configuration file:

Modify the configuration and add validation annotations:

When we start the program, we will find a direct error, can not start, the console print the following information:

Especially suitable for flexible and secure configuration.

If I want to put oAuth information in a separate configuration file, I can use this annotation with @propertysource (value ={“”}). Here xiaobian found a pit.

Is it ok to write my configuration file like this? Nothing wrong !!!!!!!!!!!!!

Yml configuration file, I can’t read it.

And then a wave of operations. What else can you do? Search Baidu, ah!

2.5.2. Directly Loading YAML

Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean loads YAML as Properties and the YamlMapFactoryBean loads YAML as a Map. You can also use the YamlPropertySourceLoader Class if you want to load YAML as a Spring PropertySource. Spring Framework provides two convenient classes for loading YAML documents. YamlPropertiesFactoryBean YAML as attribute load and YamlMapFactoryBean YAML as Map loaded. If you want to load YAML as Spring PropertySource, you can also use the YamlPropertySourceLoader class.

Spring Boot provides strong support for externalizing configuration. In addition, properties in Spring Boot applications can be read directly in different ways and formats. However, by default, @propertysource does not load YAML files.

Isn’t that nonsense? Is it ok to change the suffix to oauth.properties? I tried again in a speculative mood. If I failed again, the following words would not appear in this article !!!!

I refuse to accept, I refuse to accept, there is a solution? “I have obsessive-compulsive disorder, I want to use YML, I love deeply!!

You take care of me, not accept, operate a wave. Custom PropertySourceFactory, starting with Spring 4.3, @propertysource with factory property. You can use it to provide a custom implementation of PropertySourceFactory that handles YAML file processing.

Implementation idea:

Define a YamlPropertySourceFactory, realize PropertySourceFactory, rewrite createPropertySource method.

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    publicPropertySource<? > createPropertySource(String name, EncodedResource resource)throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        Properties properties = factory.getObject();
        assertproperties ! =null;
        return newPropertiesPropertySource(Objects.requireNonNull(resource.getResource().getFilename()), properties); }}Copy the code

Pass the custom generated Properties object into the PropertiesPropertySource to produce a new PropertySource object, end!!

Start the test again:

conclusion

Spring Boot’s annotation binding type-safe Java beans are very powerful, often used in development, choose a suitable way for the project, annotation programming, extremely powerful, great !!!!!!!!!!!!!!!!