当前位置:网站首页>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 .
边栏推荐
- Communication bus protocol I: UART
- 第一个scrapy爬虫
- I register the absolutely deleted data in the source sqlserver, send it to maxcomputer, and write the absolute data when cleaning the data
- MySQL exercise 2
- flinkcdc可以一起导mongodb数据库中的多张表吗?
- Resttemplate and ribbon are easy to use
- 协程
- Jenkins configuration pipeline
- 1.1.1 welcome to machine learning
- Plus SBOM: assembly line BOM pbom
猜你喜欢
随机推荐
【ROS进阶篇】第九讲 URDF的编程优化Xacro使用
Feign use
2022.07.24(LC_6126_设计食物评分系统)
2022.07.24(LC_6124_第一个出现两次的字母)
[micro service ~sentinel] sentinel degradation, current limiting, fusing
“蔚来杯“2022牛客暑期多校训练营2 补题题解(G、J、K、L)
2022河南萌新联赛第(三)场:河南大学 I - 旅行
scrapy爬虫爬取动态网站
SSTI template injection vulnerability summary [bjdctf2020]cookie is so stable
【七】图层显示和标注
Experimental reproduction of image classification (reasoning only) based on caffe resnet-50 network
Introduction to the scratch crawler framework
scrapy 爬虫框架简介
2.1.2 application of machine learning
PyTorch可视化
论文解读(MaskGAE)《MaskGAE: Masked Graph Modeling Meets Graph Autoencoders》
想要做好软件测试,可以先了解AST、SCA和渗透测试
Resttemplate and ribbon are easy to use
Pytorch environment configuration and basic knowledge
Numpy first acquaintance









