有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何验证bean实例是否已连接?

我正在创建一个小框架,它提供了一些abstract基类,在使用库时必须实现这些基类

如何创建一个验证例程来检查是否所有类都已实现

我想我也许可以使用spring boot的@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 {

}

我怎样才能做到这一点


共 (3) 个答案

  1. # 1 楼答案

    当您的上下文已经初始化(例如从实现ContextLoaderListener的bean)时,您可以调用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 
             }
        }
    }
    
  2. # 2 楼答案

    ApplicationListener可用于在启动后访问上下文

    public class Loader implements ApplicationListener<ContextRefreshedEvent>{
    
        public void onApplicationEvent(ContextRefreshedEvent event) {
    
           if (event.getApplicationContext().getBeansOfType(BaseCarService.class).isEmpty()) {
               // print log, throw exception, etc 
           }
        }
    
  3. # 3 楼答案

    下面的方法可以奏效,但如果只是抛出一个异常,看起来有点尴尬:

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