ContextRefreshedEvent

최진규·2023년 6월 8일
0

ContextRefreshedEvent

만약에 모든 빈이 올라가고, 이 빈들이 특정한 모듈에서만 다르게 동작되야 한다고 해보자.
이때는 해당 모듈에서의 ContextRefreshedEvent의 listener를 선언하고 여기서 빈의 설정을 override하면 된다.

간단하게 이 event는 모든 빈들이 올라가고 나서 실행된다.
여기서 applicationContext에서 빈을 꺼내서 override하면 된다.

만약에 이런 클래스가 있는 상황에서,

@Slf4j  
@Component("batchApplicationStartUp")  
public class ApplicationStartUp implements ApplicationListener<ContextRefreshedEvent> {  
  
  @Override  
  public void onApplicationEvent(ContextRefreshedEvent event) {  
    if (!(event.getApplicationContext() instanceof AnnotationConfigWebApplicationContext))  
      return;  
  
    AnnotationConfigWebApplicationContext context = (AnnotationConfigWebApplicationContext)event.getApplicationContext();  
    if (!StringUtils.contains(context.getNamespace(), "dispatcher-servlet")) {  
      return;  
    }  }  
}

라우팅 데이터 소스에 등록된 slave 데이터 소스의 설정을 override하고 싶다면
다음과 같은 코드를 작성하면 된다.

@Slf4j  
@Component("batchApplicationStartUp")  
public class ApplicationStartUp implements ApplicationListener<ContextRefreshedEvent> {  
  
  @Override  
  public void onApplicationEvent(ContextRefreshedEvent event) {  
    if (!(event.getApplicationContext() instanceof AnnotationConfigWebApplicationContext))  
      return;  
  
    AnnotationConfigWebApplicationContext context = (AnnotationConfigWebApplicationContext)event.getApplicationContext();  
    if (!StringUtils.contains(context.getNamespace(), "dispatcher-servlet")) {  
      return;  
    }  
    // slaveDataSource 꺼내기  
    DataSource slaveDataSource = context.getBean("slaveDataSource", DataSource.class);  
  
    // slaveDataSource를 basicDataSource로 캐스팅  
    BasicDataSource basicSlaveDataSource = (BasicDataSource)slaveDataSource;  
    // slave의 routing 설정 변경  
    basicSlaveDataSource.setUrl("temp url");  
  
  }  
}

이런 식으로....

profile
개발하는 개복치

0개의 댓글

Powered by GraphCDN, the GraphQL CDN