Spring IoC/DI 10-條件註解注入 Bean(Java配置實現)

條件註解注入 Bean(Java配置實現)

模擬場景

當程序在 Windows 操作系統下運行時打印 dir 命令,在 Linux 操作系統下運行時打印 ls 命令

代碼實現

  1. 定義接口
    ShowCmd.java
public interface ShowCmd {
    String show();
}
  1. 定義接口實現
// ShowCmdInLinux.java
public class ShowCmdInLinux implements ShowCmd {
    @Override
    public String show() {
        return "ls";
    }
}

// ShowCmdInWindows.java
public class ShowCmdInWindows implements ShowCmd {
    @Override
    public String show() {
        return "dir";
    }
}
  1. 定義條件
// LinuxCondition.java
public class LinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String property = conditionContext.getEnvironment().getProperty("os.name");
        return property.toLowerCase().contains("linux");
    }
}

// WindowsCondition.java
public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String property = conditionContext.getEnvironment().getProperty("os.name");
        return property.toLowerCase().contains("window");
    }
}
  1. 使用條件註解配置Bean
@Configuration
public class JavaConfig {

    @Bean("cmd")
    @Conditional(WindowsCondition.class)
    ShowCmd showCmdInWindows(){
        return new ShowCmdInWindows();
    }

    @Bean("cmd")
    @Conditional(LinuxCondition.class)
    ShowCmd showCmdInLinux(){
        return new ShowCmdInLinux();
    }
}
  1. 應用
public class TestCmd {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
        ShowCmd cmd = (ShowCmd) context.getBean("cmd");
        System.out.println(cmd.show());
    }
}
發佈了20 篇原創文章 · 獲贊 0 · 訪問量 431
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章