<!--一个博主专栏付费入口结束-->
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-d284373521.css">
<div id="content_views" class="markdown_views">
<!-- flowchart 箭头图标 勿删 -->
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
</svg>
<p>在开发项目中,经常会遇到这样的需求:项目启动之后需要进行一些初始化操作。在spring项目开发中可以使用下面两种方法完成。</p>
spring中实现代码如下。注意可以使用@Component注解,但必须在xml中扫描包,注册为组件;也可以在xml中直接配置bean,否则下面方法不会被执行。
实现ApplicationListener接口
使用@PostConstrut注解
- 1
- 2
1. 实现ApplicationListener接口
创建一个类实现ApplicationListener接口,同时监听ContextRefreshedEvent事件。
@Component
public class InitConfiguration implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent arg0) {
System.out.println("init operation");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
注意: 如果出现上面方法执行两次,可能由于在web项目中存在两个容器,
spring root context 另一个就是我们自己的 projectName-servlet
context(作为root application context的子容器),解决方法如下。
此外本人使用spring4.X实测并没有运行两次。
- 1
- 2
- 3
- 4
- 5
- 6
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(event.getApplicationContext().getParent() == null){
//root application context 没有parent,他就是老大.
//需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
2. 使用@PostConstrut注解
@Component
public class DispatcherTask {
@PostConstruct
public void init(){
System.out.println("init operation");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
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标签的作用)