SpringBoot 根据配置前缀绑定配置:@ConfigurationProperties
文章目录
- 内部 Bean 配置绑定
- 第三方 Bean 配置绑定
@ConfigurationProperties
是 Spring 在
org.springframework.boot.context.properties
包中提供的一个注解。它的作用是根据注解中配置的前缀对 SpringBoot 配置文件(即
application.xxx
)中前缀相同的配置进行属性绑定。
对于 @ConfigurationProperties
注解,通常有如下应用场景:
- 场景一:如果需要让 Spring 当中的 Bean 与
application.xxx
中相关的配置进行绑定,在单个配置绑定的情况下,使用@Value
注解十分方便,但是如果有多个配置都需要绑定的情况下,虽然仍然可以使用@Value
对其进行配置绑定,但一个个绑定太过麻烦。 - 场景二:如果需要让一个外部类(如第三方 Jar 包)中的配置,在无法修改外部类中的代码的情况下,需要将外部类与
application.xxx
中的相关配置进行绑定,需要在配置类中声明外部 Bean 并进行配置绑定。
@ConfigurationProperties
注解就可以解决上述两个问题。
内部 Bean 配置绑定
使用 @ConfigurationProperties
可以对 IOC 容器内部的 Bean 进行配置绑定。例如:
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "school")
public class SchoolProperties {
private String name;
private String address;
private String type;
}
对于以上案例的 application.yml
配置:
school:
name: 人才大学
address: 长沙市
type: A_School
上述案例中,声明了一个名为 SchoolProperties
的 Spring Bean,通过 @ConfigurationProperties(prefix = "school")
绑定 application.yml
中以 school
为前缀的三个配置 name
、address
和 type
。
第三方 Bean 配置绑定
使用 @ConfigurationProperties
也可以对 IOC 容器外部(即第三方包中提供的 Bean)进行配置绑定。例如:
@Configuration
public class SchoolConfig {
@Bean
@ConfigurationProperties(prefix = "school")
public SchoolProperties schoolProperties(){
return new SchoolProperties();
}
}
上述案例中,假设 SchoolProperties
是一个外部第三方 Jar 包中的类。因为无法修改 SchoolProperties
的源码,所以通过在一个 SchoolConfig
的配置类中手动使用 @Bean
向 Spring IOC 容器中注入了一个 SchoolProperties
类型的 Bean,并且通过 @ConfigurationProperties(prefix = "school")
将配置文件中以 school
为前缀的配置进行属性绑定。