问题描述
我知道关于Spring Autowired的问题有很多问题,但是我找不到与我类似的东西,如果抱歉,我很抱歉...
I know theres a ton of questions regarding problems with Spring Autowired, but I havent been able to find anything similar to mine, so sorry if its a dupe...
我在自动装配已创建的bean时遇到问题(调试显示该构造函数已运行),但随后没有注入.没有手动实例化的调用.我在项目中还有许多其他自动接线领域,它们工作正常.不过,最有趣的是,我在不同的项目中使用了相同的模式和配置,并且在这里有效 ...
Im having problems with autowiring a bean that is created (debugging shows that the constructor is run), but then it doesnt get injected. There are no calls of manual instantiation.I have many other autowired fields in the project and they work fine.Most amusing, though, is the fact that Ive used the same pattern and config in a different project and it works there...
现在,这是代码:
创建但未注入的bean:
The bean that gets created but not injected:
@Component("genericDao")
public class GenericHibernateJpaDao implements GenericDao {
@Autowired
protected EntityManagerFactory entityManagerfactory;
public GenericHibernateJpaDao() {
}
//getters, setters and dao methods
}
GenericDao接口仅定义方法,没有注释.
GenericDao interface only defines methods and has no annotations.
定义bean的服务超类:
Service super-class that defines the bean:
@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是
Breakpoint in service implementation at genericDao.saveOrUpdate(n);
shows genericDao to be null (this is also the line that throws NullPointerEx.)IMessageService is
@Service
@Configurable
@Transactional
application-config.xml(相关位):
application-config.xml (relevant bits):
<beans .......... default-autowire="byName">
<context:component-scan base-package="package.with.dao" />
<context:component-scan base-package="package.with.service" />
<context:spring-configured/>
我想这只是我这边的一个愚蠢的错误,但我无法弄清楚,而谷歌搜索也无济于事.
Im guessing its just some fairly stupid mistake on my side, but I just cant figure it out and googling isnt helping.
感谢您的帮助.
推荐答案
好吧,事实证明,我在调试过程中误以为前提.虽然我没有手动启动DAO bean,但是我在测试的初始化过程中创建了 service 的手动实例,因为我需要向其传递一个虚拟对象.是的...
Well, turns out I was mistaken in my premise during debugging.While I had no manual initiation of the DAO bean, I was creating a manual instance of the service in the initialization of the tests, because I needed to pass it a dummy object.So yeah...
但是,感谢大家的帮助,因为它使我意识到了这一点,并帮助我更好地理解了Spring及其注释.
Thanks to everyone for the help though, as it nudged me to this realization and helped me understand Spring and its annotations better.
这篇关于春季创建豆但不注入它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!