【发布时间】: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