发布时间:2025-06-24 00:21:43 作者:北方职教升学中心 阅读量:215
前言
从上面的使用说明中我们了解到了条件注解的大概使用方法,但是代码中还是有很多硬编码的问题。
好处:
可以实现某些配置的开关功能,如上面的例子,我们可以将UserBean换成开启缓存的配置,当property的值为true时,我们才开启缓存的配置
当有多个同名的bean时,如何抉择的问题。
3.1 创建项目
首先我们创建一个SpringBoot项目
3.1.1 导入依赖
这里我们除了springboot依赖,再添加个lombok依赖
<?xml version="1.0"encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.3</version><relativePath/><!--lookup parent from repository --></parent><groupId>com.ldx</groupId><artifactId>condition</artifactId><version>0.0.1-SNAPSHOT</version><name>condition</name><description>Demoproject forSpringBoot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
3.1.2 添加配置信息
在application.yaml 中加入配置信息
user:enable:false
3.1.3 创建User类
packagecom.ldx.condition;importlombok.AllArgsConstructor;importlombok.Data;/** * 用户信息 * @author ludangxin * @date 2021/8/1 */@Data@AllArgsConstructorpublicclassUser{privateStringname;privateIntegerage;}
3.1.4 创建条件实现类
packagecom.ldx.condition;importorg.springframework.context.annotation.Condition;importorg.springframework.context.annotation.ConditionContext;importorg.springframework.core.env.Environment;importorg.springframework.core.type.AnnotatedTypeMetadata;/** * 用户bean条件判断 * @author ludangxin * @date 2021/8/1 */publicclassUserConditionimplementsCondition{@Overridepublicbooleanmatches(ConditionContextconditionContext,AnnotatedTypeMetadataannotatedTypeMetadata){Environmentenvironment =conditionContext.getEnvironment();// 获取property user.enableStringproperty =environment.getProperty("user.enable");// 如果user.enable的值等于true 那么返回值为true,反之为falsereturn"true".equals(property);}}
3.1.5 修改启动类
packagecom.ldx.condition;importlombok.extern.slf4j.Slf4j;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.context.ConfigurableApplicationContext;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Conditional;@Slf4j@SpringBootApplicationpublicclassConditionApplication{publicstaticvoidmain(String[]args){ConfigurableApplicationContextapplicationContext =SpringApplication.run(ConditionApplication.class,args);// 获取类型为User类的BeanUseruser =applicationContext.getBean(User.class);log.info("user bean === {}",user);}/** * 注入User类型的Bean */@Bean@Conditional(UserCondition.class)publicUsergetUser(){returnnewUser("张三",18);}}
3.2 测试
3.2.1 当user.enable=false
报错找不到可用的User类型的Bean
.____ _ __ _ _ /\\ /___'_ __ _ _(_)_ __ __ _ \ \ \ \(()\___ |'_ | '_||'_ \/_` |\ \ \ \ \\/___)||_)|||||||(_||))))' |____|.__|_||_|_||_\__,|////=========|_|==============|___/=/_/_/_/::SpringBoot::(v2.5.3)Exceptionin thread "main"org.springframework.beans.factory.NoSuchBeanDefinitionException:Noqualifying bean of type 'com.ldx.condition.User' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1172)at com.ldx.condition.ConditionApplication.main(ConditionApplication.java:16)Processfinished withexitcode 1
3.2.2 当user.enable=true
正常输出UserBean实例信息
.____ _ __ _ _ /\\ /___'_ __ _ _(_)_ __ __ _ \ \ \ \(()\___ |'_ | '_||'_ \/_` |\ \ \ \ \\/___)||_)|||||||(_||))))' |____|.__|_||_|_||_\__,|////=========|_|==============|___/=/_/_/_/::SpringBoot::(v2.5.3)com.ldx.condition.ConditionApplication:user bean ===User(name=张三,age=18)
3.3 小结
上面的例子通过使用@Conditional和Condition接口,实现了spring bean的条件化注入。
实现自动化的装载。如判断当前classpath中有mysql的驱动类时(说明我们当前的系统需要使用mysql),我们就自动的读取application.yaml中的mysql配置,实现自动装载;当没有驱动时,就不加载。ConditionContext定义如2.2.1,AnnotatedTypeMetadata见名知意,就是用来获取注解的元信息的
@FunctionalInterfacepublicinterfaceCondition{booleanmatches(ConditionContextcontext,AnnotatedTypeMetadatametadata);}
2.2.1 ConditionContext
ConditionContext接口定义如下:通过查看源码可以知道,从这个类中可以获取很多有用的信息
publicinterfaceConditionContext{/** * 返回Bean定义信息 * Return the {@link BeanDefinitionRegistry} that will hold the bean definition * should the condition match. * @throws IllegalStateException if no registry is available (which is unusual: * only the case with a plain {@link ClassPathScanningCandidateComponentProvider}) */BeanDefinitionRegistrygetRegistry();/** * 返回Bean工厂 * Return the {@link ConfigurableListableBeanFactory} that will hold the bean * definition should the condition match, or {@code null} if the bean factory is * not available (or not downcastable to {@code ConfigurableListableBeanFactory}). */@NullableConfigurableListableBeanFactorygetBeanFactory();/** * 返回环境变量 比如在application.yaml中定义的信息 * Return the {@link Environment} for which the current application is running. */EnvironmentgetEnvironment();/** * 返回资源加载器 * Return the {@link ResourceLoader} currently being used. */ResourceLoadergetResourceLoader();/** * 返回类加载器 * Return the {@link ClassLoader} that should be used to load additional classes * (only {@code null} if even the system ClassLoader isn't accessible). * @see org.springframework.util.ClassUtils#forName(String, ClassLoader) */@NullableClassLoadergetClassLoader();}
三、 定义
- 2.1 @Conditional
- 2.2 Condition
- 2.2.1 ConditionContext
- 三、
4.1 创建注解
importorg.springframework.context.annotation.Conditional;importjava.lang.annotation.*;/** * 自定义条件属性注解 * <p> * 当配置的property name对应的值 与设置的 value值相等时,则注入bean * @author ludangxin * @date 2021/8/1 */@Target({ElementType.TYPE,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documented// 指定condition的实现类@Conditional({UserCondition.class})public@interfaceMyConditionOnProperty{// 配置信息的keyStringname();// 配置信息key对应的值Stringvalue();}
4.2 修改UserCondition
packagecom.ldx.condition;importorg.springframework.context.annotation.Condition;importorg.springframework.context.annotation.ConditionContext;importorg.springframework.core.env.Environment;importorg.springframework.core.type.AnnotatedTypeMetadata;importjava.util.Map;/** * 用户bean条件判断 * @author ludangxin * @date 2021/8/1 */publicclassUserConditionimplementsCondition{@Overridepublicbooleanmatches(ConditionContextconditionContext,AnnotatedTypeMetadataannotatedTypeMetadata){Environmentenvironment =conditionContext.getEnvironment();// 获取自定义的注解Map<String,Object>annotationAttributes =annotatedTypeMetadata.getAnnotationAttributes("com.ldx.condition.MyConditionOnProperty");// 获取在注解中指定的name的property的值 如:user.enable的值Stringproperty =environment.getProperty(annotationAttributes.get("name").toString());// 获取预期的值Stringvalue =annotationAttributes.get("value").toString();returnvalue.equals(property);}}
测试后,结果符合预期。
二、昵称在beanFactory中不存在时返回true.各类型间是or的关系
- @ConditionalOnBean 与上面相反,要求bean存
- @ConditionalOnMissingClass 当给定的类名在类路径上不存在时返回true,各类型间是and的关系
- @ConditionalOnClass 与上面相反,要求类存在
- @ConditionalOnCloudPlatform 当所配置的CloudPlatform为激活时返回true
- @ConditionalOnExpression spel表达式执行为true
- @ConditionalOnJava 运行时的java版本号是否包含给定的版本号.如果包含,返回匹配,否则,返回不匹配
- @ConditionalOnProperty 要求配置属性匹配条件 @ConditionalOnJndi 给定的jndi的Location必须存在一个.否则,返回不匹配
- @ConditionalOnNotWebApplication web环境不存在时
- @ConditionalOnWebApplication web环境存在时
- @ConditionalOnResource 要求制定的资源存在