超详细分析Spring的@Conditional注解 喜欢ヅ旅行 2024-03-26 22:00 18阅读 0赞 ### 前言 ### 已知@**Conditional**注解用于指定能够注册为容器中的**bean**的条件。那么本篇文章将结合示例工程,从源码入手,分析@**Conditional**注解的如下几个方面。 1. @**Conditional**注解的作用时机; 2. **Condition**的执行顺序; 3. 多个**Condition**之间的关系。 **Springboot**版本:**2.4.1** **Spring**版本:**5.3.2** ### 正文 ### #### 一. 示例工程搭建 #### 示例工程结构如下所示。 ![format_png][] **Condition**接口实现类如下所示。 public class MyControllerCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { System.out.println(this.getClass().getName()); return true; } } public class MyDaoCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { System.out.println(this.getClass().getName()); return true; } } public class MyFurtherCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { System.out.println(this.getClass().getName()); return true; } } public class MyRepositoryCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { System.out.println(this.getClass().getName()); return true; } } public class MyServiceCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { System.out.println(this.getClass().getName()); return true; } } 复制代码 业务类定义如下所示。 @Controller @Conditional(MyControllerCondition.class) public class MyController {} @Conditional(MyDaoCondition.class) public class MyDao {} public class MyFurtherService {} @Conditional(MyRepositoryCondition.class) public class MyRepository {} public class MyService {} 复制代码 配置类**MyFurtherConfig**定义如下。 @Configuration @Conditional(MyFurtherCondition.class) public class MyFurtherConfig { @Bean public MyFurtherService myFurtherService() { return new MyFurtherService(); } } 复制代码 配置类**MyConfig**定义如下。 @ComponentScan @Configuration @Import(MyDao.class) public class MyConfig { @Bean @Conditional(MyServiceCondition.class) public MyService myService() { return new MyService(); } @ [format_png]: https://image.dandelioncloud.cn/pgy_files/images/2024/03/25/4dbeecfaadbf4d55a9cc8f1d66037048.png
还没有评论,来说两句吧...