我想在一個spring singleton bean中啓動和停止一個石英調度器。但postconstruct被調用了兩次,而predestroy並沒有被調用。 This鏈接說因爲代理它自然被稱爲兩次,但這是造成postconstruct方法中的異常。我只想在加載單例bean之後調用postConstruct一次。Spring @PreDestroy和@PostConstruct註釋
1
A
回答
0
我編寫了contextloader偵聽器並更改了web.xml偵聽器,所以我只能初始化bean一次。
<listener>
<listener-class>
CustomContextLoaderListener
</listener-class>
</listener>
public class CustomContextLoaderListener extends
org.springframework.web.context.ContextLoaderListener{
Scheduler scheduler;
@Override
public void contextInitialized(javax.servlet.ServletContextEvent event) {
try{
super.contextInitialized(event);
this.scheduler= WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()).getBean(Scheduler.class);
}
@Override
public void contextDestroyed(ServletContextEvent event){
super.contextDestroyed(event);
scheduler.stopSchedulers();
}
0
你爲什麼不嘗試使用init-method或嘗試實現初始化bean。這些提供了postConstruct的替代方法。
當彈簧豆被卸載時,即當容器關閉或者通過其他方式調用ConfigurableApplicationContext方法中的close()方法時,調用preDestroy。
相關問題
- 1. 註釋@Resource,@PostConstruct和@PreDestroy是否需要<context:annotation-config>?
- 2. 運行SpringBootApplication PostConstruct和PreDestroy
- 3. 在Spring 3.0.0.RC1中使用@PostConstruct註釋
- 4. @PostConstruct註解和JSF
- 5. 使用Spring @Lazy和@PostConstruct註解
- 6. Spring Boot @PreDestroy註解不起作用
- 7. 如果不使用xml文件配置,我該如何使用@PostConstruct和@PreDestroy?
- 8. Spring @ContextConfiguration註釋,TestNG和IDEA
- 9. Spring 3和JSR-330註釋
- 10. spring @Transactional註釋
- 11. Spring @ComponentScan註釋
- 12. Spring @Value註釋
- 13. @postconstruct和@Scheduled註解在一起
- 14. @PostConstruct註釋和春天的生命週期
- 15. Spring批註與註釋
- 16. Spring名稱註釋
- 17. Spring註釋組件
- 18. Spring Scope註釋值
- 19. Spring + Hibernate ORM註釋
- 20. 註釋在Spring MVC
- 21. Spring MVC註釋@ModelAttribute
- 22. @ManagedProperty注射後@PostConstruct
- 23. 兩個Spring RequestContextFilter和@Component註釋
- 24. JBOSS 5和Spring 3驗證註釋
- 25. AOP,Spring 4 MVC和@Around註釋
- 26. Spring註釋和生命週期。
- 27. Java和Spring。事務性註釋@Transactional
- 28. 模擬對象和Spring註釋
- 29. spring-integration-kafka註釋支持和示例
- 30. Spring集成註釋和SmartLifecycle接口
init-metod也調用了兩次 – ayengin 2011-12-26 19:21:51