上下文组件扫描未找到我的自定义注释bean

时间:2012-11-23 11:23:07

标签: java spring spring-mvc annotations

您好我正在尝试为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视为空。难道我做错了什么? 谢谢。

1 个答案:

答案 0 :(得分:-1)

MigrationHandler是一个春天豆吗?如果是,为什么不自动迁移MigrationRequired。