2016-04-25 1 views
1

すべてのBeanがロードされた後、Springコンテナ内でいくつかのコードを実行するにはどうすればよいですか?私は@PostConstructを単一のBeanに使うことができますが、の後にそのコードを実行したいと思っています。 PostConstructsが呼び出されました。 可能ですか?春のポストコンテナのコンストラクション

--- UPDATE ---

私はApplicationListenerの道に従うことを試みたが、これは実装です:

私は何を得たすべてのサービスに "初期化可能" インターフェースを適用
@Component 
public class PostContructListener implements ApplicationListener<ContextRefreshedEvent> { 

    private static Logger log = LoggerFactory.getLogger(PostContructListener.class); 

    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { 
     Collection<Initializable> inits= contextRefreshedEvent.getApplicationContext().getBeansOfType(Initializable.class).values(); 
     for (Initializable initializable : inits) { 
      try{ 
       log.debug("Initialization {} ",initializable.getClass().getSimpleName()); 
       initializable.init(); 
      }catch(Exception e){ 
       log.error("Error initializing {} ",initializable.getClass().getSimpleName(),e); 
      } 
     } 
    } 
} 

私はすべてのオートワイヤーを壊してしまったのですが、その理由を理解できませんが、新しい「初期化可能」インターフェースに接続されているようです:

java.lang.IllegalArgumentException: Can not set com.service.MyService field com.controller.RestMultiController.myService to com.sun.proxy.$Proxy41 

答えて

0

あなたはこれが必要だと思います。

public class SpringListener implements ApplicationListener<ContextRefreshedEvent>{ 

     public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { 
       // do things here 
     } 
    } 

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#context-functionality-events

+0

これは、春の起動後に2回呼び出され...あなたはなぜ私に言うことができますか? – Tobia

+1

http://stackoverflow.com/questions/6164573/why-is-my-spring-contextrefreshed-event-called-twice –

関連する問題