Spring容器启动之后进行初始化操作
2017-04-28 17:13
381 查看
Spring容器启动之后进行初始化操作
在开发项目中,经常会遇到这样的需求:项目启动之后需要进行一些初始化操作。在spring项目开发中可以使用下面两种方法完成。实现ApplicationListener接口
使用@PostConstrut注解
1. 实现ApplicationListener接口
创建一个类实现ApplicationListener接口,同时监听ContextRefreshedEvent事件。ContextRefreshedEvent 事件,当一个ApplicationContext被初始化或刷新时触发。 详细参考—— [ spring事件 ]
spring中实现代码如下。注意可以使用@Component注解,但必须在xml中扫描包,注册为组件;也可以在xml中直接配置bean,否则下面方法不会被执行。
@Component public class InitConfiguration implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent arg0) { System.out.println("init operation"); } }
注意: 如果出现上面方法执行两次,可能由于在web项目中存在两个容器,spring root context 另一个就是我们自己的 projectName-servlet context(作为root application context的子容器),解决方法如下。此外本人使用spring4.X实测并没有运行两次。
@Override public void onApplicationEvent(ContextRefreshedEvent event) { if(event.getApplicationContext().getParent() == null){ //root application context 没有parent,他就是老大. //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。 } }
2. 使用@PostConstrut注解
@Component public class DispatcherTask { @PostConstruct public void init(){ System.out.println("init operation"); } }
spring xml配置扫描包:
<context:component-scan base-package="com.java.*">
component-scan标签默认情况下自动扫描指定路径下的包(含所有子包),将带有@Component、@Repository、@Service、@Controller标签的类自动注册到spring容器。对标记了 Spring’s @Required、@Autowired、JSR250’s @PostConstruct、@PreDestroy、@Resource、JAX-WS’s @WebServiceRef、EJB3’s @EJB、JPA’s @PersistenceContext、@PersistenceUnit等注解的类进行对应的操作使注解生效(包含了annotation-config标签的作用)
相关文章推荐
- Spring容器启动之后进行初始化操作
- web容器启动时,借助spring进行初始化操作
- 如何优雅的在Spring容器启动完成后进行资源初始化
- 通过Spring @PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
- 继承ContextLoaderListener在Spirng容器初始化时可以进行个性化操作
- 最佳实践--Spring容器初始化完成之后执行某个方法
- 【Spring】Springboot监听器,启动之后初始化工作
- spring 容器初始化 bean 和销毁前所做的操作
- Spring容器启动后自动执行Servlet进行预处理
- Spring容器启动后自动执行Servlet进行预处理
- 通过Spring @PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
- Spring容器初始化完之后执行某个方法
- 通过Spring @PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
- spring容器启动,初始化某个方法(init)
- spring读取配置文件初始化容器操作总结
- spring读取配置文件初始化容器操作总结
- spring读取配置文件初始化容器操作总结
- 通过Spring @PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
- Spring源码学习之: 通过Spring @PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
- Spring在Web容器启动时执行初始化方法