springboot-@ConfigurationProperties annotation

Preface

Recently, I am thinking about using java config for configuration. java config refers to spring based on java configuration. Traditional Spring is generally configured with basic xml. Later, spring 3.0 added many java config annotations, especially spring boot, which is basically all java config.

Spring configuration method

The first stage: xml configuration

In the spring 1.x era, the use of spring to develop beans that are all xml-configured. As the project expands,
we need to separate the xml configuration files into different configuration files. At that time , we need to frequently develop classes and configurations. Switch between files.

Phase 2: Annotation configuration

In the spring 2.x era, with the annotation support brought by JDK 1.5, spring provides annotations for declaring beans,
which greatly reduces the amount of configuration. At this time, there is a dispute in the spring circle: which is better, annotation configuration or xml configuration? Our final choice is to
use xml for the basic configuration of the application and user annotations for the business configuration.

The third stage: Java configuration (java config)

From spring 3.x to the present, spring provides the ability to configure Java, using Java configuration to better understand the
configured beans. Both spring 4.x and spring boot recommend using Java configuration.

Spring IOC has a very core concept-Bean. The Spring container is responsible for the instantiation, assembly and management of the Bean. XML is the most popular configuration method used to describe Beans. But with the growing development of Spring, more and more people have criticized Spring. "A lot of bad use of XML in the Spring project" is the most severe criticism. Because Spring will configure almost all business classes in XML files in the form of Beans, resulting in a large number of XML files. Using XML to configure the Bean loses the type safety check at compile time. A lot of XML configuration makes the whole project more complicated.

With the release of JAVA EE 5.0, a very important feature has been introduced-Annotations. Comments are tags for source code. These tags can be processed at the source code level or melted into the class file by the compiler. In versions after JAVA EE5, annotations have become a major configuration option. Spring uses annotations to describe the configuration of Beans compared with XML, because the class annotations are in a class source code, the benefits of type safety checking can be obtained. Can support reconstruction well.

JavaConfig uses annotations to describe the components of Bean configuration. JavaConfig is a sub-project of Spring. Compared with Spring, it is still a very young project. The current version is 1.0 M2. Use XML to configure the functions that Bean can achieve, and JavaConfig can also be implemented very well.

Let's talk about the use of @ConfigurationProperties specifically

@ConfigurationProperties

ConfigurationProperties annotations are extensively used in the Spring source code. For example, server.port is obtained from this annotation, and can be used in conjunction with other annotations to realize the on-demand configuration of Beans.

The annotation has a prefix attribute, which binds the configuration in the configuration file through the specified prefix. The annotation can be placed on the class or on the method.

Insert picture description here

As you can see from the annotation description, when the annotation is applied to the method, if you want an effective binding configuration, then the method needs to have the @Bean annotation and the class to which it belongs needs to have the @Configuration annotation.

A brief summary is: the effective operation of Sring is completed by the cooperation of Bean in the context (Bean container). Bean can be simply understood as an object. Some objects need to specify the field content, so we can bind these contents through the configuration file. Then return this bean to the container

The more common scenario is to configure read-write separation.

Configuration file content

#数据源
spring.datasource.druid.write.url=jdbc:mysql://localhost:3306/jpa
spring.datasource.druid.write.username=root
spring.datasource.druid.write.password=1
spring.datasource.druid.write.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.druid.read.url=jdbc:mysql://localhost:3306/jpa
spring.datasource.druid.read.username=root
spring.datasource.druid.read.password=1
spring.datasource.druid.read.driver-class-name=com.mysql.jdbc.Driver

java code

@Configuration
public class DruidDataSourceConfig {
    
    
    /**
     * DataSource 配置
     * @return
     */
    @ConfigurationProperties(prefix = "spring.datasource.druid.read")
    @Bean(name = "readDruidDataSource")
    public DataSource readDruidDataSource() {
    
    
        return new DruidDataSource();
    }


    /**
     * DataSource 配置
     * @return
     */
    @ConfigurationProperties(prefix = "spring.datasource.druid.write")
    @Bean(name = "writeDruidDataSource")
    @Primary
    public DataSource writeDruidDataSource() {
    
    
        return new DruidDataSource();
    }
}

Some people may be more confused when they see this. The prefix does not specify the fully qualified name of the configuration, so how does it bind the configuration?

I believe we certainly understand @Value notes, it can 全限定名进行配置的绑定, ConfigurationProperties here is in fact similar to the use of multiple simultaneous binding @Value, DataSource object binding is the type of the object, but also 隐式绑定, meaning that configuration 文件编写的时候需要与对应类的字段名称相同, such as the above-mentioned spring .datasource.druid.write.url=jdbc:mysql://localhost:3306/jpa, of course, you can also write a configuration at will, such as spring.datasource.druid.write.uuu=www.baidu.com, this When you only need to add the following parameters in the annotation

The above has completed the configuration of multiple data sources, paving the way for the separation of read and write

Configuration file

spring.datasource.url=jdbc:mysql://127.0.0.1:8888/test?useUnicode=false&autoReconnect=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

Entity class

@ConfigurationProperties(prefix = "spring.datasource")
@Component
public class DatasourcePro {
    
    

    private String url;

    private String username;

    private String password;

    // 配置文件中是driver-class-name, 转驼峰命名便可以绑定成
    private String driverClassName;

    private String type;

    public String getUrl() {
    
    
        return url;
    }

    public void setUrl(String url) {
    
    
        this.url = url;
    }

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }

    public String getDriverClassName() {
    
    
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
    
    
        this.driverClassName = driverClassName;
    }

    public String getType() {
    
    
        return type;
    }

    public void setType(String type) {
    
    
        this.type = type;
    }
}

usage

@Controller
@RequestMapping(value = "/config")
public class ConfigurationPropertiesController {
    
    

    @Autowired
    private DatasourcePro datasourcePro;

    @RequestMapping("/test")
    @ResponseBody
    public Map<String, Object> test(){
    
    

        Map<String, Object> map = new HashMap<>();
        map.put("url", datasourcePro.getUrl());
        map.put("userName", datasourcePro.getUsername());
        map.put("password", datasourcePro.getPassword());
        map.put("className", datasourcePro.getDriverClassName());
        map.put("type", datasourcePro.getType());

        return map;
    }
}

to sum up

1. @ConfigurationProperties and @value have the same function, but the writing of @ConfigurationProperties is more convenient.
2. For @ConfigurationProperties POJO类的命名比较严格,因为它必须和prefix的后缀名要一致, 不然值会绑定不上, the special suffix name is "driver-class-name". The naming rule is下划线转驼峰 就可以绑定成功,所以就是 “driverClassName”

Intrusion

Guess you like

Origin blog.csdn.net/m0_46267375/article/details/109128945