【问题标题】:Context Component Scan not finding my custom annotated beans上下文组件扫描未找到我的自定义注释 bean
【发布时间】:2012-11-11 18:13:00
【问题描述】:

您好,我正在尝试为 Spring MVC webapp 编写自定义注释。但是 Spring applicationContext 无法检测到带注释的类。这是我的相关代码。

带注释的类:

@Component
@MigrationRequired(migrateFrom="Tiff",migrateTo="PDF-A")
public class WordTemplate extends Template{

}

CustomAnnotationDefinition:

@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MigrationRequired {

    String migrateFrom() default "Tiff";
    String migrateTo() default "PDF-A";
}

用于检测 ContextLoading 上的注释的类

public class MigrationHandler implements ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {

        final Map<String, Object> myMaps = applicationContext.getBeansWithAnnotation(MigrationRequired.class);
        System.out.println("inside after properties set" + myMaps );//**Always giving an empty set**
        for (final Object myMap : myMaps.values()) {
            final Class<? extends Object> myClass = myMap .getClass();
            final MigrationRequired annotation = myClass .getAnnotation(MigrationRequired.class);
            System.out.println("Found myClass: " + myClass + ", with tags: " + annotation.migrateFrom());
        }
    }

    @Override
    public void setApplicationContext(final ApplicationContext applicationContext)
            throws BeansException {
        System.out.println("This is called");
        this.applicationContext = applicationContext;
    }
}

applicationContext.xml相关配置

<bean id="migrationHandler" class="com.test.annotation.MigrationHandler"/>

<context:component-scan base-package="com.test" >
<context:include-filter type="annotation"expression="com.test.annotation.MigrationRequired"/>
</context:component-scan>
<!--Other beans definition-->

所以在MigrationHandler afterPropertiesSet() 的方法中,我总是将myMaps 设为空。难道我做错了什么? 谢谢你。

【问题讨论】:

  • 不确定,但我认为您需要在注释MigrationRequired 中添加@Component 注释,尝试添加并检查。
  • 尝试将String name();@Component 一起添加到您的注释中,就像@Nandkumar 提到的那样。不需要额外的工作。
  • @White 感谢添加名称字段对我有用。非常感谢

标签: java spring spring-mvc annotations


【解决方案1】:

MigrationHandler 是不是一个spring bean?如果是,为什么不自动装配 MigrationRequired。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多