我的问题:
为什么Spring自动扫描对我不起作用?
我不想使用bean.xml
文件,而是让系统自行扫描bean。
我使用Spring AnnotationConfigApplicationContext
。
Bean具有@Component
批注,并且其包包含在scan
中,但是当尝试获取Bean时,它具有NoSuchBeanDefinitionException
。
我有一个以下结构的Maven项目
- module A
- module B (depends on A)
- module C (depends on B)
(由于
@Configuration
类的初始化也是一个问题,因为用于初始化应用程序上下文的代码在module A
中是通用的,而bean在module B
中并且无法从A实例化。)在
module A
中,有一个代码可以加载ApplicationContext
。我有一个用于获取应用程序上下文的singelton。
package com.mycode.my;
public class AppContext {
private static ApplicationContext ctx;
public static ApplicationContext getApplicationContext() {
if (ctx == null)
ctx = new AnnotationConfigApplicationContext("com.mycode");
return ctx;
}
}
在模块B中,有接口和Bean在使用它
package com.mycode.third;
public interface MyBean{
void runSomething();
}
package com.mycode.third;
@Component
public class MyBeanImpl implements MyBean{
public void runSomething(){
}
}
问题:
当我尝试从模块C获取bean时:
public class MyImpl{
public void doTheJob(){
MyBean bean1 = AppContext.getApplicationContext().getBean("myBean")
}
}
我得到:
org.springframework.beans.factory.NoSuchBeanDefinitionException
任何想法如何使它工作或更好的方法?
最佳答案
默认情况下,组件(或任何其他bean原型)的bean名称是:类名,首字母小写。因此,您的bean被命名为myBeanImpl
。
在这里,您可以在查找中将接口名称指定为Bean名称。
它不能以这种方式工作,因为如果Spring使用该接口作为bean名称,那么您将无法实现该接口的多个实现。
任何想法如何使它工作或更好的方法?
更好的方法是不直接使用spring工厂获取bean,而是使用自动装配功能对其进行注入。
@ContextConfiguration(classes = MyAppConfig.class)
public class MyImpl{
private MyBean bean;
// Autowire constructor
public MyImpl(MyBean bean){
this.bean = bean;
}
public void doTheJob(){
// you can use bean now
}
}
更好的方法是使用Spring Boot,只要您遵守标准,它就需要您进行一些其他配置。