Spring-Condition设置
为了满足不同条件下生成更为合适的bean,可以使用condition配置其条件。假如有一个bean,id为magicBean,只有当其具有magic属性时才生成,方法如下:
javaConfig模式:只需要在声明bean的地方加上@Conditional即可
1 package com.myapp; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Conditional; 5 6 public class MagicBean { 7 @Bean//显式声明一个bean,id默认为方法名 8 @Conditional(MagicExistsConditional.class)//生成bean的条件判断,参数类型为class,接受返回的布尔值,为true则生成bean否则不生成 9 public MagicBean magicBean(){ 10 return new MagicBean(); 11 } 12 }
其参数(MagicExistsConditional.class)是如何编写呢?
1 package com.myapp; 2 3 import org.springframework.context.annotation.Condition; 4 import org.springframework.context.annotation.ConditionContext; 5 import org.springframework.core.env.Environment; 6 import org.springframework.core.type.AnnotatedTypeMetadata; 7 8 public class MagicExistsConditional implements Condition{ 9 10 @Override 11 public boolean matches(ConditionContext arg0, AnnotatedTypeMetadata arg1) { 12 // TODO Auto-generated method stub 13 Environment env=arg0.getEnvironment();//获取上下文环境 14 return env.containsProperty("magic");//检查是否包含magic属性 15 } 16 17 }
这里只是通过ConditionContext类型的arg0得到Environment类型的env,通过env调用方法判断是否存在magic属性。
而ConditionContext和AnnotatedTypeMetadata都是接口,里面定义了许多方法,详见《Spring实战(第4版)》P75-P78。
God, Grant me the SERENITY, to accept the things I cannot change,
COURAGE to change the things I can, and the WISDOM to know the difference.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix