当前位置:网站首页>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 .
边栏推荐
- What is ci/cd?
- 想要白嫖正则大全是吧?这一次给你个够!
- scrapy 设置随机的user_agent
- Maskgae: masked graph modeling meets graph autoencoders
- LeetCode 1184. 公交站间的距离
- MySQL练习二
- WPF project introduction 1 - Design and development of simple login page
- Pairwise comparison of whether the mean values between R language groups are the same: pairwise hypothesis test of the mean values of multiple grouped data is performed using pairwise.t.test function
- Is the securities account opened by qiniu safe? How to open an account
- I register the absolutely deleted data in the source sqlserver, send it to maxcomputer, and write the absolute data when cleaning the data
猜你喜欢

基于Caffe ResNet-50网络实现图片分类(仅推理)的实验复现

【C语言进阶】动态内存管理

2.1.2 机器学习的应用

第一个scrapy爬虫

485通讯( 详解 )

Alibaba cloud technology expert Qin long: reliability assurance is a must - how to carry out chaos engineering on the cloud?

Technical management essay
Software testing interview question: Please list the testing methods of several items?

想要做好软件测试,可以先了解AST、SCA和渗透测试

弹性盒子(Flex Box)详解
随机推荐
软件测试流程包括哪些内容?测试方法有哪些?
Ansible
2022.07.24(LC_6124_第一个出现两次的字母)
Kyligence 入选 Gartner 2022 数据管理技术成熟度曲线报告
Ecological profile of pytorch
1.1.1 welcome to machine learning
SSTI template injection vulnerability summary [bjdctf2020]cookie is so stable
PyTorch主要模块
协程
Communication bus protocol I: UART
Build a series of vision transformer practices, and finally meet, Timm library!
Synergetic process
919. Complete binary tree inserter: simple BFS application problem
Jenkins configuration pipeline
WPF项目入门1-简单登录页面的设计和开发
2.1.2 机器学习的应用
【11】 Production and adjustment of vector and grid data Legends
R language uses LM function to build multiple linear regression model, step function to build forward stepwise regression model to screen the best subset of prediction variables, and scope parameter t
【ROS进阶篇】第九讲 URDF的编程优化Xacro使用
想要做好软件测试,可以先了解AST、SCA和渗透测试