当前位置:网站首页>Use of Spirng @conditional conditional conditional annotation
Use of Spirng @conditional conditional conditional annotation
2022-07-25 12:38:00 【Ugly base】
1、 brief introduction
@Conditional yes Spring 4.0 Put forward a new annotation , When the labeled object meets all the conditions , To register as Spring Medium bean.
@Conditional The definitions in the source code are as follows :
@Target({
ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
Class<? extends Condition>[] value();
}
You can see @Conditional It can be used on classes or methods . The specific usage is as follows :
1、 In the annotation or meta annotation @Component Mark on the class of the component ;
2、 As a meta annotation, it is directly marked on other annotations ;
3、 It's marked with @Bean Annotate the method .
@Conditional There is a note value attribute , Its value can only be Condition An array of types , Use @Conditional Must be specified ( Multiple Condition It's the relationship with , Multiple conditions need to be met . By default, it is specified in the defined order , Can pass @Order Yes Condition Sort ).
Condition It refers to specific conditions , It's an interface , You have to implement it yourself .
@FunctionalInterface
public interface Condition {
/** * Determine whether the conditions match */
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}
Condition Is a functional interface , only one matches Method , return true Express Component You can register as Spring Medium bean. There are two parameters :
1、 ConditionContext: Context information representing the condition ;
public interface ConditionContext {
/** * Acquisition and holding BeanDefinition Registration Center for ,BeanDefinition yes Spring bean The definition of ,BeanDefinitionRegistry It can be used to register or find BeanDefinition. */
BeanDefinitionRegistry getRegistry();
/** * obtain BeanFactory,BeanFactory yes spring The most basic container , There is spring Of bean example */
@Nullable
ConfigurableListableBeanFactory getBeanFactory();
/** * Get the environment information of the current application */
Environment getEnvironment();
/** * Get the current ResourceLoader, It can be used to load various resources */
ResourceLoader getResourceLoader();
/** * Get to load other classes ClassLoader */
@Nullable
ClassLoader getClassLoader();
}
2、 AnnotatedTypeMetadata: Represents annotation meta information on a class or method .
public interface AnnotatedTypeMetadata {
/** * Return the annotation details of direct annotation * @since 5.2 */
MergedAnnotations getAnnotations();
/** * Determine whether the element has an annotation or meta annotation for the given type definition */
default boolean isAnnotated(String annotationName) {
return getAnnotations().isPresent(annotationName);
}
/** * Get the annotation attribute of the given type , Consider attribute rewriting */
@Nullable
default Map<String, Object> getAnnotationAttributes(String annotationName) {
return getAnnotationAttributes(annotationName, false);
}
/** * Get the annotation attribute of the given type , Consider attribute rewriting */
@Nullable
default Map<String, Object> getAnnotationAttributes(String annotationName, boolean classValuesAsString) {
MergedAnnotation<Annotation> annotation = getAnnotations().get(annotationName, null, MergedAnnotationSelectors.firstDirectlyDeclared());
if (!annotation.isPresent()) {
return null;
}
return annotation.asAnnotationAttributes(Adapt.values(classValuesAsString, true));
}
/** * Get all attributes of all annotations of a given type , Do not consider attribute rewriting */
@Nullable
default MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationName) {
return getAllAnnotationAttributes(annotationName, false);
}
/** * Get all attributes of all annotations of a given type , Do not consider attribute rewriting */
@Nullable
default MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationName, boolean classValuesAsString) {
Adapt[] adaptations = Adapt.values(classValuesAsString, true);
return getAnnotations().stream(annotationName)
.filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes))
.map(MergedAnnotation::withNonMergedAttributes)
.collect(MergedAnnotationCollectors.toMultiValueMap(map -> map.isEmpty() ? null : map, adaptations));
}
}
2、 actual combat
The goal to achieve : According to different environment , Configure different thread pools . Steps are as follows :
1、 Customize Condition, Matching condition :
/** * @Des Match the local development environment * @Author jidi * @Email [email protected] * @Date 2022/7/23 */
public class ProfilesActiveOfDevCondition implements Condition {
private static final String DEV = "dev";
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
// Get configuration properties spring.profiles.active
Environment environment = conditionContext.getEnvironment();
String property = environment.getProperty("spring.profiles.active");
return Objects.equals(DEV, property);
}
}
/** * @Des Match the production environment * @Author jidi * @Email [email protected] * @Date 2022/7/23 */
public class ProfilesActiveOfProCondition implements Condition {
private static final String PRO = "pro";
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
// Get configuration properties spring.profiles.active
Environment environment = conditionContext.getEnvironment();
String property = environment.getProperty("spring.profiles.active");
return Objects.equals(PRO, property);
}
}
2、 Define a specific thread pool , adopt @Conditional The annotation specifies the environment in which each takes effect :
/** * @Des * @Author jidi * @Email [email protected] * @Date 2022/7/23 */
@Configuration
@Slf4j
public class ApplicationConfig {
/** * development environment */
@Bean
@Conditional(value = {
ProfilesActiveOfDevCondition.class})
public ThreadPoolExecutor devExecutor(){
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2,
5,
60,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100),
new ThreadPoolExecutor.CallerRunsPolicy());
// Pre initialize all core threads
executor.prestartAllCoreThreads();
log.info(" Initialize the development environment thread pool !");
return executor;
}
/** * Production environment */
@Bean
@Conditional(value = {
ProfilesActiveOfProCondition.class})
public ThreadPoolExecutor proExecutor(){
ThreadPoolExecutor executor = new ThreadPoolExecutor(
5,
20,
60,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1024),
new ThreadPoolExecutor.CallerRunsPolicy());
// Pre initialize all core threads
executor.prestartAllCoreThreads();
log.info(" Initialize the production environment thread pool !");
return executor;
}
}
3、 Configure properties in the configuration file spring.profiles.active, Start the project , You can load different thread pools according to different configurations .
3、 other @Conditional Extended annotation
except @Conditional Explanatory notes ,Spring There are also many other built-in conditional annotations , And their matching logic has been implemented , You can make . There are mainly the following notes :
1、@ConditionalOnBean: When Spring There is a specified in the container Bean Effective when ;
2、@ConditionalOnMissingBean: When Spring The specified... Does not exist in the container Bean Effective when ;
3、@ConditionalOnClass: When Spring There is a specified in the container Class Effective when ;
4、@ConditionalOnMissingClass: When Spring The specified... Does not exist in the container Class Effective when ;
5、@ConditionalOnProperty: It takes effect when the specified attribute meets the matching conditions ;
6、@ConditionalOnResource: It takes effect when there are specified resources under the classpath ;
7、@ConditionalOnWebApplication: When the project is web Effective at the time of the project ;
8、@ConditionalOnNotWebApplication: When the project is not web Effective at the time of the project ;
9、@ConditionalOnExpression: When SpEL The expression takes effect when it is true ;
10、@ConditionalOnJava: When satisfied JVM Version takes effect ;
11、@ConditionalOnJndi: When specifying JNDI Effective when it exists .
边栏推荐
- PyTorch的生态简介
- SSTI 模板注入漏洞总结之[BJDCTF2020]Cookie is so stable
- What is ci/cd?
- perf 性能调试
- 1.1.1 welcome to machine learning
- Pytorch project practice - fashionmnist fashion classification
- [advanced C language] dynamic memory management
- Eureka usage record
- Fiddler抓包APP
- [micro service ~sentinel] sentinel degradation, current limiting, fusing
猜你喜欢
随机推荐
启牛开的证券账户安全吗?是怎么开账户的
R language uses the ggarrange function of ggpubr package to combine multiple images, and uses the ggexport function to save the visual images in JPEG format (width parameter specifies width, height pa
scrapy爬虫爬取动态网站
2.1.2 机器学习的应用
Jenkins配置流水线
Table partition of MySQL
Ecological profile of pytorch
我想问DMS有没有定时备份某一个数据库的功能?
JS 将伪数组转换成数组
Implement anti-theft chain through referer request header
【六】地图框设置
【七】图层显示和标注
Kyligence was selected into Gartner 2022 data management technology maturity curve report
Detailed explanation of flex box
【九】坐标格网添加以及调整
3.2.1 what is machine learning?
2022河南萌新联赛第(三)场:河南大学 I - 旅行
I register the absolutely deleted data in the source sqlserver, send it to maxcomputer, and write the absolute data when cleaning the data
logstash
【7】 Layer display and annotation







