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

         <!--一个博主专栏付费入口结束-->
        <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标签的作用)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值