简体   繁体   中英

How to validate if a bean instance has been wired?

I'm creating a small framework that provides some abstract base classes that have to be implemented when using the library.

How can I create a validation routine that checks if indeed all classes have been implemented?

I thought I could maybe use @ConditionalOnMissingBean of spring-boot, but that does nothing so far. Anyhow, my goal would be:

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

//must be implemented
public abstract BaseCarService {

}

How can I achieve this?

You can do this calling ApplicationContext.getBeansOfType(BaseCarService.class) when your context has been initialized (for example from bean that implements ContextLoaderListener ), ie something like the following:

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

ApplicationListener could be used to get access to the Context after startup.

public class Loader implements ApplicationListener<ContextRefreshedEvent>{

    public void onApplicationEvent(ContextRefreshedEvent event) {

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

The following will work, but looks a little awkward if you are just going to throw an exception:

@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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM