我知道有很多关于 Spring Autowired 问题的问题,但我还没有找到任何与我的类似的东西,如果它是一个骗局,我很抱歉......
我在 Autowiring 创建的 bean 时遇到问题(调试显示构造函数已运行),但它没有被注入(inject)。没有手动实例化的调用。 我在项目中还有许多其他 Autowiring 的字段,它们工作正常。 不过,最有趣的是,我在不同的项目中使用了相同的模式和配置,并且在那里工作...
现在,这是代码:
创建但未注入(inject)的 bean:
@Component("genericDao")
public class GenericHibernateJpaDao implements GenericDao {
@Autowired
protected EntityManagerFactory entityManagerfactory;
public GenericHibernateJpaDao() {
}
//getters, setters and dao methods
}
GenericDao 接口(interface)只定义了方法,没有注释。
定义 bean 的服务父类(super class):
@Configurable
public abstract class AbstractService {
@Autowired
protected GenericDao genericDao;
//getters, setters
}
服务实现(声明位):
@Service
@Component
public class WechatMessageService extends AbstractService implements IMessageService {
genericDao.saveOrUpdate(n);
处的服务实现断点显示 genericDao 为空(这也是抛出 NullPointerEx 的行。)
IMessageService 是
@Service
@Configurable
@Transactional
application-config.xml(相关位):
<beans .......... default-autowire="byName">
<context:component-scan base-package="package.with.dao" />
<context:component-scan base-package="package.with.service" />
<context:spring-configured/>
我猜这只是我这边的一些相当愚蠢的错误,但我就是想不通,谷歌搜索也无济于事。
感谢您的帮助。
最佳答案
如果您没有启用加载时编织(为了与 AspectJ 一起工作),您将不需要使用 @Configurable
注释。
尝试从 AbstractService
中删除 @Configurable
,因为它是一个抽象类。还要从WechatMessageService
中移除@Component
,因为你已经有了@Service
,所以不需要@Component
。
为您的 AbstractService
类尝试以下操作:
public abstract class AbstractService {
@Resource(name = "genericDao")
protected GenericDao genericDao;
//getters, setters
}
使用 @Resource
可以更好地按名称 Autowiring ,因此您不需要使用限定符。
关于java - Spring创建bean但不注入(inject)它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29259464/