@ComponentScan
public class BeanApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(BeanApplication.class, args);
TestBean bean = context.getBean(TestBean.class);
System.out.println(bean);
}
}
@Component
@ConditionalOnMissingBean(TestBean.class)
class TestBean {
}
在上面的代码中,并没有获取到testBean这个bean。
期望的结果是@ComponentScan可以扫描所有带有@Component的类,然后根据条件@ConditionalOnMissingBean(TestBean.class)加载bean。可是实际上并没有加载,想知道怎么才能加载。
以下2种情况是可以成功加载的
第一种:
@Import(TestBean.class)
public class BeanApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(BeanApplication.class, args);
TestBean bean = context.getBean(TestBean.class);
System.out.println(bean);
}
}
@ConditionalOnMissingBean(TestBean.class)
class TestBean {
}
第二种:
@ComponentScan
public class BeanApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(BeanApplication.class, args);
TestBean bean = context.getBean(TestBean.class);
System.out.println(bean);
}
}
@Component
class TestBean {
}
但是这两种情况分别无法达到如下需求
第一种:不能根据@Component扫描到需要加载的bean
第二章:不能根据@ConditionalOnMissingBean进行条件装配
想请教以下,有什么好的解决方案没?