2017-01-24 7 views
0

웹 응용 프로그램을 시작할 때 타이머 및 로깅을 초기화하고 싶습니다. ContextListener를 사용할 수 없습니다. 스프링 구성 요소를 포함하고 있지 않기 때문입니다. "afterWebAppHasLoadedAndEverythingyIsSetUp()"와 같은 간단한 후크가 필요합니다. 존재합니까?Java Web App에서 시작 후크를 선언하는 방법

답변

2

ApplicationContext는 Bean을로드 할 때 특정 유형의 이벤트를 게시합니다.

ApplicationContext의 이벤트 처리는 ApplicationEvent 클래스 및 ApplicationListener 인터페이스를 통해 제공됩니다. 따라서 Bean이 ApplicationListener를 구현하면 ApplicationEvent가 ApplicationContext에 게시 될 때마다 해당 Bean에 통지됩니다.

다음 이벤트

,174 다음과 같이

  • 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으로 등록하면됩니다.

1

스프링 부트 (권장)를 사용하는 경우 다음 CommandLineRunner 빈을 사용하여 응용 프로그램을 시작한 후 초기화 작업을 실행할 수 있습니다. 당신은 모든 봄 콩을 준비 할 수있을 것입니다, 아래 코드 스 니펫입니다.

@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); 
    } 
} 
관련 문제