spring 项目加载完立刻执行

来源:互联网 发布:非线性最优化算法 编辑:程序博客网 时间:2024/05/08 04:37
我的目的是想在项目加载完毕之后,需要进行一些初始化的动作,比如从数据库查询数据,缓存起来.

找到了三种方式:

  1. 第一种方式
    写一个类,实现BeanPostProcessor,这个接口有两个方法
    (1)postProcessBeforeInitialization方法,在spring中定义的bean初始化前调用这个方法;
    (2)postProcessAfterInitialization方法,在spring中定义的bean初始化后调用这个方法;
    这个虽然也能执行,但是是每次加载一个bean都会去执行,不太满足我的要求,我只需要一次就ok了,但是这个接口针对某个专门的bean有用

  2. 第二种方式 编写一个实现ApplicationListener的listener类

@Servicepublic class StartupListener implements           ApplicationListener<ContextRefreshedEvent > {      public static String ShopNum ;      @Autowired      ShopService shopService;      @Override      public void onApplicationEvent(ContextRefreshedEvent event) {           if ( event.getApplicationContext (). getParent() == null) {               // TODO 这里写下将要初始化的内容               Shop shopByShopNum = shopService                         .getShopByShopNum ("e7-80-2e-e8-6c-a6" );                System.out .println ("----------------------------" );           } }}
亲测可用,但是我这个项目用不了,是项目比较特殊,加载了两次spring MV容器,导致执行两次,.
  1. 最后一种方式编写InitializingBean的实现类
@Servicepublic class Test implements InitializingBean{      @Autowired      ShopService shopService;      @Override      public void afterPropertiesSet() throws Exception {           Shop shopByShopNum = shopService.getShopByShopNum( "e7-80-2e-e8-6c-a6");           System.out .println ("----------------------------" );      }}

项目在加载完毕后立刻执行afterPropertiesSet 方法 ,并且可以使用spring 注入好的bean

4.第四种就是servlet,但是他不能使用spring 的bean 还需要手动获取,比较麻烦.

0 0