SpringBoot's @ConfigurationProperties, @Autowired, @Conditional annotations

1. @ConfigurationProperties + @EnableConfigurationProperties + @Autowired注解

In the resources/application.properties file, define key and value in the format: prefix. class property = value. As follows:

server.port = 8088

# 格式:前缀.类属性 = 值
user.test.name = user1

If the attribute of the User class is userName, the parameter isuser.test.user-name

Use the @ConfigurationProperties annotation to modify the User class, and assign the value matching the prefix in application.properties to the User class property . The User class must have a parameterless constructor

package com.hh.springbootTest.myBean;

import org.springframework.boot.context.properties.ConfigurationProperties;

// 将application.properties中user.test前缀对应的值赋值给User类属性
@ConfigurationProperties(prefix = "user.test")
public class User {

    private String name;

    public User() {

    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "User{" + "name='" + name + "'}";
    }
}

Use @EnableConfigurationProperties to enable the configuration binding function of the User class . The User class is automatically added to the container. Must be used with @Configuration annotation. As follows:

package com.hh.springbootTest.myConfig;

import com.hh.springbootTest.myBean.User;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

// 开启User类的配置绑定功能。User类会自动添加到容器中
@EnableConfigurationProperties(User.class)
@Configuration
public class MyConfig {

}

In addition to using @EnableConfigurationProperties to add User to the container, directly using @Component annotation on the User class, etc., will also add User to the container

Use the @Autowired annotation to automatically obtain the User class object from the IOC container , as follows:

package com.hh.springbootTest.myController;

import com.hh.springbootTest.myBean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    // 从IOC容器自动获取User类对象
    @Autowired
    User user;

    @RequestMapping("/user")
    public User userName1() {
        return user;
    }

}

Then visit http://localhost:8088/user, the displayed effect is as follows:
ConfigurationProperties test effect

1.1 configuration Custom configuration parameter auto-completion function

In order to improve our development efficiency, in application.properties or application.yaml, we can realize the auto-completion function for our customized configuration parameters. The operation is as follows:

Add dependencies in pom.xml

......省略部分......
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

......省略部分......
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            
......省略部分......

Then re-run the springboot project. Afterwards, in application.properties or application.yaml, our custom configuration parameters will have the auto-completion function

2. @Conditional annotation

@Conditional has many annotations, the commonly used ones are as follows:

  • @ConditionalOnBean: Only when there are specified components in the IOC container, the operation is performed
  • @ConditionalOnMissingBean: There is no specified component in the IOC container, and the operation is performed
  • @ConditionalOnClass(name = "com.hh.xxx"): maven only executes the operation if it has a class that depends on the specification
  • @ConditionalOnMissingClass(value = "com.hh.xxx"): maven does not rely on the specified class before performing the operation
  • @ConditionalOnWebApplication: The program is a web application of springboot, only to perform operations
  • @ConditionalOnNotWebApplication: The program is not a springboot web application, only to perform operations
  • @ConditionalOnProperty: There are specified properties in the program before the operation is performed
  • @ConditionalOnResource: Only when there is a specified configuration file in the program, the operation is performed
  • @ConditionalOnJava: The program only performs operations based on the specified java version
  • @ConditionalOnSingleCandidate: Only one instance of the class specified in the IOC container will perform the operation

Let's take @ConditionalOnMissingBean as an example to explain:

User class, as follows:

package com.hh.springbootTest.myBean;

public class User {

    private String name;

    public User(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "User{" + "name='" + name + "'}";
    }
}

@ConditionalOnBean can modify both classes and methods . The characterEncodingFilter bean is added to the IOC container after the operation is performed, so the condition here is false. Then MyConfig and userName1 will not be added to the IOC container. As follows:

package com.hh.springbootTest.myConfig;

import com.hh.springbootTest.myBean.User;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

// characterEncodingFilter这个bean在执行完该操作后,才添加到IOC容器,所以这里的条件结果为false
// 则不会向IOC容器添加MyConfig和userName1
@ConditionalOnBean(name = "characterEncodingFilter")
@Configuration
public class MyConfig {

    @Bean
    public User userName1() {
        return new User("user1");
    }


}

Execute the program and check that there is no component named userName1 in the IOC container, as shown below:

package com.hh.springbootTest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {

        ConfigurableApplicationContext applicationContext =
                SpringApplication.run(MyApplication.class, args);

        // 判断IOC容器是否包含指定name的组件
        boolean containsUser1 = applicationContext.containsBean("userName1");
        System.out.println(containsUser1);      // 返回的结果是:false
    }
}

Guess you like

Origin blog.csdn.net/yy8623977/article/details/127656236