首页 > 编程知识 正文

什么是有条件呼转,unconditional

时间:2023-05-03 16:27:12 阅读:107851 作者:925

@Conditional @Conditional是Spring4新提供的注释,用于按照一定条件进行判断,满足条件后在容器中注册bean。

* @ authorphillipwebb * @ authorsambrannen * @ since 4.0 * @ see condition */@ target ({ element type.type, element type.method } @ retention (retention policy.runtime ) documented public @ interface conditional (/* * all ) @ that MP extends Condition[] value (; }参数是Condition类的集合,让我们来看看Condition接口

* @ authorphillipwebb * @ since 4.0 * @ seeconfigurationconditional * @ seeconditioncontext */@ functionaling determineiftheconditionmatches.* @ paramcontexttheconditioncontext * @ parammetadatathemetadataofthe { @ linkorg.spring framework.core.type.annotationmetadataclass } * or { @ linkorg.spring framework.core.type.methodmetadatamethod } being checked * @ return { @ code true } iftheconditionditionmmmed * or { @ code false } tovetotheannotatedcomponent ' sregistration */boolean matches (conditioncontextcontext,annotedtypemed

测试

创建person类,创建配置类,并返回linux和Windows类。

@ data @ allargsconstructor @ noargsconstructorpublicclassperson { privatestring name; 私有整合者; //类中的主键批量设置:启用满足当前条件并为此类设置的所有bean注册@ conditional (window condition.class ) ) configurationpublicclass 如果系统是Windows,请在容器中注册*'bill'*。 linux,*/@注册conditional ({ window condition.class } ) @ conditional (Linux condition.class ) ) bean ) (Linus ) 10 }2创建两个类LinuxCondition。 每个WindowsCondition实现一个Condition界面作为@Contional注释的值。

//windowpublicclasswindowconditionimplementscondition {/* * * @ param context :条件下的上下文* @param metadata : @ overridepublicbooleanmatches (conditioncontextcontext, 是否可以获得annotatedtypemetadatametadata (//Linux//1. IOC使用的beanfactoryconfigurablelistablebeanfactorybeanfactory=context //3 .获取当前环境信息的环境环境=context.get环境(; //4.bean定义的注册类beandefinitionregistryregistry=context.getregistry (; string property=environment.getproperty (' OS.name ); 属性.内容(windows ) ) ) { return true; } return false; }//linuxpublicclasslinuxconditionimplementscondition { @ overridepublicbooleanmatches (conditioncontextcontext,anotateded string property=environment.getproperty (' OS.name ); 属性.内容(“Linux”) { return true; } return false; }这两个类实际上获得并判断当前的运行环境,返回true,false .分别添加@Conditional注释并执行:

发现只注入了Bill类,将执行环境变更为linux,试着进行了一次测试

//类中主键的统一设置:满足当前条件时,将启用为该类配置的所有bean注册//@ conditional ({ window condition.class } ) configuration pube

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。

  • 相关阅读