@ConditionalOnProperty注解
@ConditionalOnProperty注解的作用是根据配置文件中的属性值来决定是否启用某个组件或功能。可以用于根据配置文件中的属性值来决定是否启用某个Bean或配置。
该注解的常用属性如下:
name
:配置文件中的属性名,可以使用prefix.name
的形式来指定。havingValue
:配置文件中属性的值,如果与该属性值相同,则启用该 Bean 或者配置。matchIfMissing
:如果配置文件中没有该属性,则默认启用该 Bean 或者配置。value
:与name
属性相同,用于指定配置文件中的属性名。prefix
:配置文件中的前缀,用于指定属性名的前缀。
示例代码1
@Configuration
@ConditionalOnProperty(name = "myapp.feature.enabled", havingValue = "true")
public class MyFeatureConfig {
// ...
}
上述代码中,如果配置文件中 myapp.feature.enabled
属性的值为 true
,则启用 MyFeatureConfig
配置类。如果没有该属性,则默认启用该配置类。如果属性值不为 true
,则不启用该配置类。
示例代码2
另外,@ConditionalOnProperty
还支持多个属性的判断,可以使用 value
属性来指定多个属性名,例如:
@Configuration
@ConditionalOnProperty(value = {"myapp.feature.enabled", "myapp.feature.type"}, havingValue = "true")
public class MyFeatureConfig {
// ...
}
上述代码中,如果配置文件中 myapp.feature.enabled
和 myapp.feature.type
属性的值都为 true
,则启用 MyFeatureConfig
配置类。
示例代码3
@Configuration
@ConditionalOnProperty(prefix = "myconfig", value = "enabled", havingValue = "true", matchIfMissing = false)
public class MyConfig {
// 定义Bean
}
@ConditionalOnProperty注解的作用是根据配置文件中的myconfig.enabled属性值来决定是否启用MyConfig配置类中的Bean定义。如果myapp.enabled属性值为true,则启用该配置类中的Bean定义;如果myconfig.enabled属性值为false,则不启用该配置类中的Bean定义。如果myconfig.enabled属性值不存在,则默认不启用该配置类中的Bean定义。
@ConfigurationProperties注解
@ConfigurationProperties注解是Spring Boot中用于绑定配置属性的注解,它可以将配置文件中的属性值绑定到Java对象的属性上。下面是@ConfigurationProperties注解的几种使用场景
场景一
使用@ConfigurationProperties和@Component注解到bean定义类上,这里@Component代指同一类实例化Bean的注解。
// 将类定义为一个bean的注解,比如 @Component,@Service,@Controller,@Repository
// 或者 @Configuration
@Component
// 表示使用配置文件中前缀为stu1的属性的值初始化该bean定义产生的的bean实例的同名属性
// 在使用时这个定义产生的bean时,其属性name会是Lucifer
@ConfigurationProperties(prefix = "stu1")
@Data
public class StudentConfig {
private String name;
}
application.properties配置文件中:
stu1.name=Lucifer
场景二
使用@ConfigurationProperties和@Bean注解在配置类的Bean定义方法上。以数据源配置为例:
@Configuration
public class DataSourceConfig {
@Primary
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
}
将前缀为“spring.datasource.primary”的属性,赋值给DataSource对应的属性值。
@Configuration注解的配置类中通过@Bean注解在某个方法上将方法返回的对象定义为一个Bean,并使用配置文件中相应的属性初始化该Bean的属性。
场景三
使用@ConfigurationProperties注解到普通类,然后再通过@EnableConfigurationProperties定义为Bean。
@ConfigurationProperties(prefix = "stu1")
@Data
public class StudentConfig {
private String name;
}
这里Student对象没有使用@Component相关注解。
Student类对应的使用形式如下:
@SpringBootApplication
@EnableConfigurationProperties({StudentConfig.class})
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
或者在@Configuration的配置类上加@EnableConfigurationProperties({StudentConfig.class})
就可以使用
@Autowired
StudentConfig studentConfig;
参考博客:https://blog.csdn.net/wo541075754/article/details/104575745