SpringBoot basic configuration in detail

SpringBoot project has some basic configuration, such as starting pattern (banner), such as the default configuration file application.properties, and the associated default configuration items.

The sample project code: https://github.com/laolunsi/spring-boot-examples


A start pattern banner

Banner.txt written into the resources folder, and then start the project can modify the default pattern.

Generated on banner, you can go to some special website.

For example: https: //www.bootschool.net/ascii


Second, the application configuration file

2.1 application.properties/yml

Under resources will usually generate a default application.properties file that contains SpringBoot project global configuration file. Inside the configuration items it is usually like this:

server.port=8080

In this file we can add framework support configuration items, such as port number of projects, JDBC data source connection, log level, and so on.

Now more popular is the properties file instead yml file. Yml file format yaml is this:

server:
    port: 8080

Yml role and properties is the same. Yml and the benefits are obvious - more write legible.

Call each other using the property $ {name}:

eknown:
    email: [email protected]
    uri: http://www.eknown.cn
    title: 'hello, link to ${eknown.uri} or email to ${eknown.email}'

Links: SpringBoot all official configuration properties


More than 2.2 environment configuration file

Developers usually have more than one application environment, such as common dev / prod, there will be a test, and even some other custom environments, SpringBoot support flexible switch configuration file.

Define a new configuration file need to follow the following format: application-{profile}.propertiesorapplication-{profile}.yml

For example, there are now two dev and prod environment, I need to create two files outside application.yml file:

  1. application-dev.yml

    server:
       port: 8080
  2. application-prod.yml

    server:
      port: 8081

Then by application.yml in application.profiles.active={profile}to enable the configuration specified:

application:
    profiles:
      active: dev

In addition to specifying the configuration file in application.yml in, you can also specify the start command:java -jar xxx.jar --spring.profiles.active=dev


2.2 custom configuration item and get it

It describes two ways to obtain a single configuration items and obtain multiple configuration items.

For example:

eknown:
    email: [email protected]
    uri: http://www.eknown.cn

2.2.1 Use @Value annotation get a single configuration item

@Value("${eknown.email}")
private String email;

@Value("${eknown.uri}")
private String url;

Note: When using @Value annotations, where the class must be the Spring container management, which is annotated defined @ Component, @ Controller, @ Service and other categories.

2.2.2 acquire multiple configuration items

First, we define a bean class, acquiring a plurality of configuration items by @Value:

@Component
public class MyConfigBean {
  
}

Then we get to get these values ​​by method:

@RestController
public class BasicAction {
  
  @Autowired
  private MyConfigBean myConfigBean;

}

Second, using annotations @ConfigurationProperties:

@Component
@ConfigurationProperties(perfix="eknown")
public class MyConfigBean {

  private String email;
  private String uri;
}

Here only needs to specify a prefix by prefix, the following values ​​are automatically adjusted.

Here we also used @Component annotations to make this spring container management MyConfigBean.

Furthermore, we need to introduce @Component, in turn coupled @EnableConfigurationProperties ({MyConfigBean.class}) based on the Application to start the startup configuration.

Note: We are here from the main configuration file, which is SpringBoot default application-profile file to obtain configuration data.

The custom configuration files, such as configuration items test.yml obtain this form from the situation is a little less the same.


Third, custom profiles

The above describes the configuration files are springboot the beginning of the default application file. If you want to customize a configuration file it, such as test.yml or test.properties, how to obtain one of the configuration items it?

Use @PageResource annotations can be.

First we look at the file properties to read the contents of the custom:

test.properties

hello.time=2019.11.19
hello.name=eknown

Configuration class definitions:

@Configuration
@PropertySource("classpath:test.properties")
//@PropertySource("classpath:test.yml") // 注意,yml文件不能直接这样写,会读不出数据
@ConfigurationProperties(prefix = "hello")
public class TestConfiguration {
    private String name;
    private String time;

    // hide get and set methods
}

have a test:

@RestController
@RequestMapping(value = "test")
public class TestAction {

    @Autowired
    private TestConfiguration testConfiguration;

    @GetMapping(value = "config")
    public String test() {
        return testConfiguration.getName() + "<br/>" + testConfiguration.getTime();
    }
}


If the properties file into yml file it?

We tried it and found:

Read at the data?

Analyze @PropertySource notes, found PropertySourceFactory its use is DefaultPropertySourceFactory.

This class source code is as follows:

public class DefaultPropertySourceFactory implements PropertySourceFactory {
    public DefaultPropertySourceFactory() {
    }

    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
    }
}

This class can only deal with properties file, the file can not be processed yml. So we need to customize a YmlSourceFactory.

public class YamlSourceFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        return new YamlPropertySourceLoader().load(resource.getResource().getFilename()
                , resource.getResource()).get(0);
    }
}

Then define the class test.yml config file:

@Configuration
@PropertySource(value = "classpath:test.yml", encoding = "utf-8", factory = YamlSourceFactory.class)
@ConfigurationProperties(prefix = "yml.hello")
public class TestYamlConfiguration {
    private String name;
    private String time;

    // hide get and set methods
}

NOTE: In order to distinguish test.properties and test.yml, test.yml herein yml.hello attributes to begin.

Write this test:

    @Autowired
    private TestYamlConfiguration ymlConfiguration;

    @GetMapping(value = "yml")
    public String testYml() {
        return "yml config: <br/>" + ymlConfiguration.getName() + "<br/>" + ymlConfiguration.getTime();
    }

access:


Fourth, the supplementary @ConfigurationProperties

Some of the information online, in order to be used in conjunction @ConfigurationProperties, also used @EnableConfigurationProperties comment.

It has been tested and found:

  1. Profile configuration information is read, using @ConfigurationProperties + @ Component / @ Configuration, or @ConfigurationProperties + Add @EnableConfigurationProperties ({class}) starting from SpringBoot default class. Both methods can solve the problem

  2. Reads the configuration information from a non-default configuration file, you need to use @PropertySource comment. Also in two ways:

    2.1 @PropertySource + @ConfigurationProperties + @Component/@Configuration

    + @ConfigurationProperties + presence of 2.2 @PropertySource @ Component / @ Configuration + @EnableConfigurationProperties, the second way is a problem that must be used @Component or comment, if you do not use, it will lead to read configuration information is null, but the program does not It is given; if employed, will result in the set method of the bean class is performed twice (i.e. generating the same type of two bean class). This way is not recommended!

Guess you like

Origin www.cnblogs.com/eknown/p/11897014.html