2014-09-10 3 views
1

라이브러리를 사용할 때 구현해야하는 기본 클래스 인 abstract을 제공하는 작은 프레임 워크를 만들고 있습니다.빈 인스턴스가 연결되었는지 확인하는 방법은 무엇입니까?

실제로 모든 클래스가 구현되었는지 확인하는 유효성 검사 루틴을 만들 수 있습니까?

스프링 부트의 @ConditionalOnMissingBean을 사용할 수 있다고 생각했지만 지금까지는 아무 것도하지 않습니다. 아무튼 내 목표는 다음과 같습니다.

@Configuration 
@EnableAutoConfiguration 
public class AppCfg { 
    @ConditionalOnMissingBean(BaseCarService.class) //stupid exmaple 
    public void validate() { 
     System.out.println("MISSING BEAN!!"); 
    } 
} 

//must be implemented 
public abstract BaseCarService { 

} 

어떻게하면됩니까?

+0

'@ ConditionalOnMissingBean'은 bean이 존재하지 않을 때 전혀 트리거되지 않습니다? – geoand

+0

전혀 아니요 출력이 없습니다. – membersound

+0

'@ ConditionalOnMissingBean'은 "Bean X가 누락되면이 bean (또는 설정)을 사용하십시오"라는 의미를 가지고 있습니다. 따라서 구성 요소 또는 구성과 함께 사용할 때만 유용합니다. – zeroflagL

답변

1

당신은 즉, 다음과 같이 사용자의 컨텍스트 (ContextLoaderListener를 구현 빈에서 예를 들어) 초기화 된 경우 ApplicationContext.getBeansOfType(BaseCarService.class)를 호출이 작업을 수행 할 수 있습니다

public class BeansValidator impelements ContextLoaderListener { 
    public void contextInitialized(ServletContextEvent event) { 
     if (ApplicationContext.getBeansOfType(BaseCarService.class).isEmpty()) { 
       // print log, throw exception, etc 
     } 
    } 
} 
+0

내가 웹 앱 안에 있지 않고 로컬 comand 라인 앱에 있다면? 'ContextLoaderListener' 나'ApplicationContext'도 없습니다. – membersound

+0

왜? 'ApplicationContext'는 Spring에서 가장 기본적인 것이다. 이것은 모든 bean을 작성하고 인스턴스를 관리하는 팩토리입니다. 이것은 봄입니다. 그래서, 그것은 항상 존재합니다. – AlexR

+0

그래, @PostConstruct와 함께 가야 할까, 아니면'ContextLoaderListener'와 비슷한 클래스가 있습니까? – membersound

0

다음은 작동을하지만, 만약 조금 어색하게 보인다

@Configuration 
@EnableAutoConfiguration 
public class AppCfg { 

    @ConditionalOnMissingBean(BaseCarService.class) 
    @Bean 
    public BaseCarService validate() { 
     throw new NoSuchBeanDefinitionException("baseCarService"); //or do whatever else you want including registering a default bean 
    } 
} 
1

ApplicationListener는 시작 후 Context에 액세스하는 데 사용할 수 있습니다.

public class Loader implements ApplicationListener<ContextRefreshedEvent>{ 

    public void onApplicationEvent(ContextRefreshedEvent event) { 

     if (event.getApplicationContext().getBeansOfType(BaseCarService.class).isEmpty()) { 
      // print log, throw exception, etc 
     } 
    } 
관련 문제