我已将基于 Spring 4.0 的项目从 xml 转换为 javaconfig。
在初始化时,我的一个 bean 需要通过 Spring @Service ( buildingService
) 访问 Hibernate 以从 DB 中获取一些配置数据。bean 初始化如下所示:
@Bean
@DependsOn({ "transactionManager", "webSocketHandler", "buildingService" })
Smarty smarty() {
Smarty bean = new Smarty();
bean.init(); // I also tried @Bean(initMethod = "init") with no difference
return bean;
}
问题是在 中bean.init()
,服务被访问,失败并带有NullPointerException
.
我添加buildingService
了,@DependsOn
但没有帮助。
可能在!?@Service
之后处理 -annotated 类。@Bean
我可以自己初始化@Service
-annotated 类吗?
编辑 1
感谢到目前为止的所有反馈!
我需要添加一些细节:
buildingService 不是 a @Bean
,而是 a @Service
,看起来像这样:
@Service("buildingService")
@Transactional
public class BuildingService {
...
public List<Building> getAll() {
final Session session = sessionFactory.getCurrentSession();
final Query query = session.createQuery("from Building order by name");
return query.list();
}
...
}
Smarty 是一个 Spring 托管的 Bean,并在一个带注释的@Configuration
类中初始化,该类正在执行根上下文的初始化。
Smarty 直接依赖于 buildingService,如下所示:
@Resource(name = "buildingService")
private BuildingService buildingService;
我尝试使用注释Smarty.init()
,@PostConstruct
但这并没有改变任何东西。
请注意,第一件事Smarty.init()
是调用buildingService.getAll();