Mastering these springboot configuration methods will double your work efficiency!

Multiple configuration methods of springboot

  • The java configuration mainly relies on java classes and some annotations. The more commonly used annotations are:

  • @Configuration: Declare a class as a configuration class instead of xml file

  • @Bean: Declare on the method, add the return value of the method to the Bean container instead of the label

  • @Value: Basic type or String property injection

  • @PropertySource: Specify an external property file

  • Take the Druid connection pool configuration as an example, the database name is springboot_test

method one

<!--pom.xml -->
<dependency> 
    <groupId>com.alibaba</groupId>              
    <artifactId>druid</artifactId> 
    <version>1.1.6</version> 
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
# src/resources/jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/bos
jdbc.username=root
jdbc.password=123456
//src\main\java\com\itheima\config\DruidConfig.java
@Configuration
@PropertySource("classpath:jdbc.properties")
public class DruidConfig {
    @Value("${jdbc.url}")
    String url;
    @Value("${jdbc.driverClassName}")
    String driverClassName;
    @Value("${jdbc.username}")
    String username;
    @Value("${jdbc.password}")
    String password;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

Interpretation:

  • @Configuration: Declare that our DruidConfig is a configuration class

  • @PropertySource: The path of the specified property file is: classpath:jdbc.properties

  • @Value injects a value for the attribute (only basic type or String)

  • @Bean declares the dataSource() method as a method of registering a Bean, and Spring will automatically call this method and add the return value of the method to the Spring container.

Way two

<!--pom.xml -->
<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid</artifactId>
     <version>1.1.6</version>
</dependency>
<dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <scope>runtime</scope>
</dependency>
<!-- ============不添加在IDEA 会报红,但并不影响功能 ================= -->
<dependency>
     <groupId> org.springframework.boot </groupId>
     <artifactId>spring-boot-configuration-processor</artifactId>
     <optional>true</optional>
</dependency>
<!--============================================================== -->
# src/resources/application.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/bos
jdbc.username=root
jdbc.password=123456
//src\main\java\com\itheima\config\DruidConfig.java
@ConfigurationProperties(prefix = "jdbc")
public class DruidProperties {
    private String url;
    private String driverClassName;
    private String username;
    private String password;

    public String getUrl() {
        return url;
    }

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

    public String getDriverClassName() {
        return driverClassName;
    }

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

    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;
    }
}
//src\main\java\com\itheima\config\DruidConfig.java
@Configuration
@EnableConfigurationProperties(DruidProperties.class)
public class DruidConfig {
    @Bean
    public DataSource dataSource(DruidProperties dp) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dp.getDriverClassName());
        dataSource.setUrl(dp.getUrl());
        dataSource.setUsername(dp.getUsername());
        dataSource.setPassword(dp.getPassword());
        return dataSource;
    }
}

Interpretation:

  • The @ConfifigurationProperties annotation declares that the current class is a property reading class, and each property is defined on the class. The name must be consistent with the latter part of the jdbc. in the property file.

  • @EnableConfigurationProperties() declares the property reading class to be used. There are three injection methods for using this class

1. @Autowired injection

//src\main\java\com\itheima\config\DruidConfig.java
@Configuration
@EnableConfigurationProperties(DruidProperties.class)
public class DruidConfig {
    @Autowired
    private DruidProperties dp;
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        //setter
        return dataSource;
    }
}

2. Constructor injection

```
//src\main\java\com\itheima\config\DruidConfig.java
@Configuration
@EnableConfigurationProperties(DruidProperties.class)
public class DruidConfig {
    private DruidProperties dp; 
    public DruidConfig(DruidProperties dp){ this.dp = dp; }
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        //setter
        return dataSource;
    }
}

```

3. As a method parameter injection of @Bean (used in this example)

//src\main\java\com\itheima\config\DruidConfig.java
@Configuration
@EnableConfigurationPerProperties(DruidProperties.class)
public class DruidConfig {
    @Bean
    public DataSource dataSource(DruidProperties dp) {
        DruidDataSource dataSource = new DruidDataSource();
        //setter
        return dataSource;
    }
}

Method 2 solves the problem that @Value cannot read object attributes (such as user.friend.name) through the attribute reading class, but it seems to be more troublesome

Method three (recommended)

In fact, if only one bean needs to be used for a section of attribute, we don't need to inject it into a class.

<!--pom.xml -->
<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid</artifactId>
     <version>1.1.6</version>
</dependency>
<dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <scope>runtime</scope>
</dependency>
<!-- ============不添加在IDEA 会报红,但并不影响功能 ================= -->
<dependency>
     <groupId> org.springframework.boot </groupId>
     <artifactId>spring-boot-configuration-processor</artifactId>
     <optional>true</optional>
</dependency>
<!--============================================================== -->
# src/resources/application.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/bos
jdbc.username=root
jdbc.password=123456
@Configuration
public class DruidConfig {
    @Bean
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
        return new DruidDataSource();
    }
}

Way Four

<!--pom.xml -->
<dependency> 
    <groupId>com.alibaba</groupId>              
    <artifactId>druid</artifactId> 
    <version>1.1.6</version> 
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
# src/resources/application.properties
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/bos
spring.datasource.username=root
spring.datasource.password=123456

Thinking: Why does this way do not require configuration classes to read configuration information?

When starting the class to run the main method, check the SpringApplication construction method, and trace as follows
Mastering these springboot configuration methods will double your work efficiency!

Mastering these springboot configuration methods will double your work efficiency!

Mastering these springboot configuration methods will double your work efficiency!

Mastering these springboot configuration methods will double your work efficiency!

It is easy to find that it obtains the class name information from META-INF/spring.factories and stores it in a one-key multi-value Map. Open spring.factories and debug comparison

Mastering these springboot configuration methods will double your work efficiency!

It is found that the key is the blue part of the file, and the value is the green part. Looking back, it is not difficult to find that it generates instances of these acquired classes and injects them into the IOC container.

Open DataSourceProperties and find that this is not the second way?
Mastering these springboot configuration methods will double your work efficiency!

Click into DataSourceProperties.class
Mastering these springboot configuration methods will double your work efficiency!

to sum up:

When we add the dependency, the DataSourceAutoConfiguration is automatically loaded when the startup class is executed, the DataSourceProperties class is read, and the information is read in application.xml according to the default prefix spring.datasource

At last

Mastering these springboot configuration methods will make it easier for you to deal with things at work. If you think the article is helpful to you, please give me a thumbs up. Your support is the biggest motivation for my creation!

Guess you like

Origin blog.51cto.com/14966465/2542899