[英]Java annotation scanning with spring
我有几个需要用名称注释的类,因此我将注释定义为
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface JsonUnmarshallable {
public String value();
}
现在,需要此注释的类定义为
@JsonUnmarshallable("myClass")
public class MyClassInfo {
<few properties>
}
我使用下面的代码来扫描注释
private <T> Map<String, T> scanForAnnotation(Class<JsonUnmarshallable> annotationType) {
GenericApplicationContext applicationContext = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(applicationContext, false);
scanner.addIncludeFilter(new AnnotationTypeFilter(annotationType));
scanner.scan("my");
applicationContext.refresh();
return (Map<String, T>) applicationContext.getBeansWithAnnotation(annotationType);
}
问题是返回的映射包含["myClassInfo" -> object of MyClassInfo]
但是我需要映射包含"myClass"
作为键,这是Annotation的值而不是bean名称。
有办法吗?
只需获取注释对象并提取值即可
Map<String,T> tmpMap = new HashMap<String,T>();
JsonUnmarshallable ann;
for (T o : applicationContext.getBeansWithAnnotation(annotationType).values()) {
ann = o.getClass().getAnnotation(JsonUnmarshallable.class);
tmpMap.put(ann.value(),o);
}
return o;
让我知道是否不清楚。
就我而言,我这样写:
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(JsonUnmarshallable.class));
Set<BeanDefinition> definitions = scanner.findCandidateComponents("base.package.for.scanning");
for(BeanDefinition d : definitions) {
String className = d.getBeanClassName();
String packageName = className.substring(0,className.lastIndexOf('.'));
System.out.println("packageName:" + packageName + " , className:" + className);
}
也许您可以使用http://scannotation.sourceforge.net/框架来实现这一目标。
希望能帮助到你。
您可以向ClassPathBeanDefinitionScanner提供一个自定义BeanNameGenerator ,它可以查找注释的值并将其作为Bean名称返回。
我认为遵循这些思路的实现应该对您有用。
package org.bk.lmt.services;
import java.util.Map;
import java.util.Set;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
public class CustomBeanNameGenerator extends AnnotationBeanNameGenerator{
@Override
protected boolean isStereotypeWithNameValue(String annotationType,
Set<String> metaAnnotationTypes, Map<String, Object> attributes) {
return annotationType.equals("services.JsonUnmarshallable");
}
}
将此添加到以前的扫描器代码中: scanner.setBeanNameGenerator(new CustomBeanNameGenerator());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.