SpringBoot根據註解@Conditional判斷注入那個物件 這裡以判斷作業系統為例
/*
* 需要被注入物件的介面
*/
public interface User {
public void getOsName();
}
/*
* 被注入物件
*/
public class WindowUser implements User{
public void getOsName() {
System.out.println("windows");
}
}
/*
* 被注入物件
*/
public class LunixUser implements User{
public void getOsName() {
System.out.println("lunix");
}
}
/*
* 程式入口
*/
@Configuration
@ComponentScan(value="demo")
public class App {
@Bean("user")
@Conditional(ConditionalImpl.class)
public User windowUser() {
return new WindowUser();
}
@Bean("user")
@Conditional(ConditionalImpl.class)
public User lunixUser() {
return lunixUser();
}
}
/*
* test
*/
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
User user =(User) context.getBean("user");
user.getOsName();
}
}