【问题标题】:How to determine that the ApplicationConfig.class is marked with a custom annotation如何确定 ApplicationConfig.class 是否标有自定义注解
【发布时间】:2016-01-16 13:01:50
【问题描述】:

我想根据是否存在标记ApplicationConfig.class 的自定义注释来启用应用程序功能,如下所示:

@FooBar(enabled = true)
@Configuration
@ComponentScan(basePackageClasses = Application.class, excludeFilters = @Filter({Controller.class, Configuration.class}))
@EnableJpaRepositories("com.package.repository")
class ApplicationConfig { 
    // Application specific configs and bean defs.
}

自定义注解命名为FooBar:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface FooBar   {
    boolean enabled() default true;
}

在应用程序启动期间,我想检测这个类(或任何其他类/bean)是否被这个注解注解。

这是我的尝试,部分基于此similar question,它包括两种确定正在使用注释的方法。

@Component
public class MyClassWithEventListeners implements ApplicationContextAware {

@Autowired
ApplicationEventPublisher applicationEventPublisher;

@Autowired
ApplicationContext applicationContext;


@EventListener
void contextRefreshedEvent(ContextRefreshedEvent event) {
    ApplicationContext applicationContext = event.getApplicationContext();
    applicationContext.getClassLoader();

    AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();

    String[] names = event.getApplicationContext().getBeanDefinitionNames();

    for (String name : names) {
        Object o = autowireCapableBeanFactory.getBean(name);
        if (AopProxyUtils.ultimateTargetClass(o).isAnnotationPresent(FooBar.class)) {
            System.out.println("Found class annotated with FooBar");
        }
    }

}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
    List<String> beanNames = getBeansWithAnnotation(FooBar.class);
    if(beanNames !=null){
        System.out.println("Found class annotated with FooBar");
    }
}

public List<String> getBeansWithAnnotation(Class<? extends Annotation> type) {
    Predicate<Map<String, Object>> filter = Predicates.alwaysTrue();
    return getBeansWithAnnotation(type, filter);
}

public List<String> getBeansWithAnnotation(Class<? extends Annotation> type, Predicate<Map<String, Object>> attributeFilter) {

    List<String> result = Lists.newArrayList();

    ConfigurableListableBeanFactory factory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
    for (String name : factory.getBeanDefinitionNames()) {
        BeanDefinition bd = factory.getBeanDefinition(name);

        if (bd.getSource() instanceof StandardMethodMetadata) {
            StandardMethodMetadata metadata = (StandardMethodMetadata) bd.getSource();

            Map<String, Object> attributes = metadata.getAnnotationAttributes(type.getName());
            if (null == attributes) {
                continue;
            }

            if (attributeFilter.apply(attributes)) {
                result.add(name);
            }
        }
    }

    return result;
}
}

contextRefreshedEvent() 和 setApplicationContext() 方法都被调用,但都无法检测到自定义注解。

我观察到我的ApplicationConfig.class 出现在bean/类列表中,但显示如下:

com.package.config.ApplicationConfig$$EnhancerBySpringCGLIB$$15073fb3@196887

  • 这是什么EnhancedBySpring?
  • Spring 如何添加功能? @EnableJpaRepositories 添加存储库。我想为自己的目的复制此功能。

【问题讨论】:

  • 你试过简单的ApplicationContext().findAnnotationOnBean(beanname, annotationType)吗?
  • 同意:启用的值有点无意义。感谢您提供有关 @Import 的提示,这在未来可能会有用。

标签: java spring spring-mvc annotations spring-boot


【解决方案1】:

核心容器实际上支持这些东西,因此无需破解上下文。当您在配置类上添加@EnableXYZ 时,您可能会受益于阅读正在发生的事情。例如@EnableCaching 或@EnableJms 的工作方式几乎相同:

接口使用@Import 进行元注释,这会导致上下文加载更多的bean。 enabled 部分在 IMO 有点没用。注释的存在与否起着相同的作用,而且更加明确。

【讨论】:

  • 这对找到我上面发布的答案最有帮助。在查看@EnableXXXX 背后的代码时,我发现了将我引向上述代码的提示。
【解决方案2】:

也许您可以使用 Class 提供的实用程序而不是 AoP 提供的实用程序?

@Test
public void testAccess(){
    SomeAnnotatedClass annotatedClassInstance = new SomeAnnotatedClass();

    Assert.assertNotNull(annotatedClassInstance.getClass().getAnnotation(FooBar.class));
}

【讨论】:

    【解决方案3】:

    我对此进行了进一步研究,并找到了两种可能的解决方案。第一个只是检测自定义注释是否存在:

    @Component
    public class MyClassWithEventListeners {
    
    @EventListener
    void contextRefreshedEvent(ContextRefreshedEvent event) throws NoSuchFieldException, IllegalAccessException {
        ApplicationContext applicationContext = event.getApplicationContext();
        String[] annotations = applicationContext.getBeanNamesForAnnotation(FooBar.class);
        if (annotations != null && annotations.length > 0) {
            System.out.println("Annotation found");
        } else {
            System.out.println("Annotation not found");
        }
    }
    }
    

    第二种使用反射来获取注解中设置的值。在这种情况下,enabled 的值。

    @Component
    public class MyClassWithEventListeners {
    
    @EventListener
    void contextRefreshedEvent(ContextRefreshedEvent event) throws NoSuchFieldException, IllegalAccessException {
        ApplicationContext applicationContext = event.getApplicationContext();
        AnnotationConfigWebApplicationContext annotationContext = ((AnnotationConfigWebApplicationContext) applicationContext);
    
        for (Field field : annotationContext.getClass().getDeclaredFields()) {
            if ("annotatedClasses".equals(field.getName())) {
                field.setAccessible(true);
                Set<Class<?>> classes = (Set<Class<?>>) field.get(annotationContext);
                for (Class clazz : classes) {
                    for (Annotation annotation : clazz.getDeclaredAnnotations()) {
                        if (annotation.annotationType().isAssignableFrom(FooBar.class)) {
                            enabled = ((ServiceRegistration) annotation).enabled();
                            System.out.println("Enabled: " + enabled);
                        }
                    }
                }
            }
        }
    }
    }
    

    这似乎有点笨拙。我想知道是否没有更优雅的方法来解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 2020-11-24
      相关资源
      最近更新 更多