您的位置:首页 > 编程语言 > Java开发

Spring容器启动之后进行初始化操作

2017-04-28 17:13 344 查看

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