2017-01-24 1 views

答えて

2

ApplicationContextは、Beanをロードするときに特定のタイプのイベントを発行します。

ApplicationContextのイベント処理は、ApplicationEventクラスとApplicationListenerインターフェイスを介して提供されます。したがって、BeanがApplicationListenerを実装する場合、ApplicationEventがApplicationContextにパブリッシュされるたびに、そのBeanに通知されます。

次のイベントがスプリング

  • によって提供されるContextRefreshedEvent
  • ContextStartedEvent
  • ContextStoppedEvent
  • ContextClosedEvent

を次のようにまずApplicationListenerの実装を作成

import org.springframework.context.ApplicationListener; 
import org.springframework.context.event.ContextStartedEvent; 

public class CStartEventHandler 
    implements ApplicationListener<ContextStartedEvent>{ 

    public void onApplicationEvent(ContextStartedEvent event) { 
     System.out.println("ContextStartedEvent Received"); 
    } 
} 

次に、クラスをBeanとしてSpringに登録するだけです。

1

私が推奨するSpringブートを使用している場合、アプリケーションの起動後に次のCommandLineRunner Beanを使用して初期化作業を実行できます。あなたはすべての春の豆を準備することができるでしょう、以下はコードスニペットです。

@Configuration 
@ComponentScan 
@EnableAutoConfiguration 
public class MyApplication extends SpringBootServletInitializer { 

    // here you can take any number of object which is anutowired automatically 
    @Bean 
    public CommandLineRunner init(MyService service, MyRepository repository) { 

     // do your stuff with the beans 

     return null; 
    } 

    @Override 
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
     return application.sources(MyApplication.class); 
    } 

    public static void main(String[] args) { 
     SpringApplication.run(MyApplication.class, args); 
    } 
} 
関連する問題