• 【Spring】条件注解


    🎈博客主页:🌈我的主页🌈
    🎈欢迎点赞 👍 收藏 🌟留言 📝 欢迎讨论!👏
    🎈本文由 【泠青沼~】 原创,首发于 CSDN🚩🚩🚩
    🎈由于博主是在学小白一枚,难免会有错误,有任何问题欢迎评论区留言指出,感激不尽!🌠个人主页



    🌟 一、条件注解

    可以根据条件,向 Spring 容器中注册 Bean,比如,我们有一个展示所有文件的命令,该命令在 Windows 上是 dir,在 Linux 上则是 ls,我们希望系统能够根据运行的环境,自动展示该命令的值。
    首先定义一个命令展示接口:

    public interface ShowCmd {
    	public String showcmd();
    }
    
    
    • 1
    • 2
    • 3
    • 4

    然后,Windows 和 Linux 分别实现该接口:

    public class WindowsShowCmd implements ShowCmd{
    	public WindowsShowCmd() {
    		System.out.println("windows init");
    	}
    
    	@Override
    	public String showcmd() {
    		return "dir";
    	}
    }
    
    public class LinuxShowCmd implements ShowCmd{
    	public LinuxShowCmd() {
    		System.out.println("linux init");
    	}
    
    	@Override
    	public String showcmd() {
    		return "ls";
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    接下来,创建两个条件,系统将根据这两个条件来判断是否将 Bean 注册到 Spring 容器中:

    public class WindowsConditional implements Condition {
    	@Override
    	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    		String osName = context.getEnvironment().getProperty("os.name");
    		System.out.println(osName);
    		return osName.toLowerCase().contains("windows");
    	}
    }
    
    public class LinuxConditional implements Condition {
    	@Override
    	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    		String osName = context.getEnvironment().getProperty("os.name");
    		return osName.toLowerCase().contains("linux") || osName.toLowerCase().contains("mac");
    	}
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    注意,虽然这里写了两个 Bean,但是实际上向 Spring 容器中注册的 Bean 只有一个
    在这里插入图片描述
    所以从 Spring 容器中获取到的就是一个 Bean:

    public class demo {
    	public static void main(String[] args) {
    		//ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
    		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(JavaConfig.class);
    		ShowCmd bean = ctx.getBean(ShowCmd.class);
    		String showcmd = bean.showcmd();
    		System.out.println(showcmd);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    条件注解有两个经典的使用场景:

    • 多环境切换

    • Spring Boot 中的自动化配置

  • 相关阅读:
    R语言ggplot2可视化:基于aes函数中的fill参数和shape参数自定义绘制分组折线图并添加数据点(散点)、设置可视化图像的主题为theme_bw
    高精度除法的实现
    Vue考试题单选、多选、判断页面渲染和提交
    Redis 键值设计使用总结
    mycat的部署及测试
    深度学习基础
    [附源码]Python计算机毕业设计SSM开放式在线课程教学与辅助平台(程序+LW)
    服务器操作集合
    深度学习的数学原理与实现 笔记一
    YOLO系列目标检测算法-Scaled-YOLOv4
  • 原文地址:https://blog.csdn.net/m0_46635265/article/details/133036558