2

我需要用名称注释的类很少,因此我将注释定义为

@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"作为键,这是注释的值而不是 bean 名称。

有没有办法做到这一点?

4

4 回答 4

5

只需获取注释对象并拉出值

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;

如果不清楚,请告诉我。

于 2012-05-11T10:59:12.823 回答
5

就我而言,我写如下:

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);
}
于 2016-08-08T07:03:25.153 回答
0

也许您可以使用http://scannotation.sourceforge.net/框架来实现这一点。

希望能帮助到你。

于 2012-05-11T10:17:40.217 回答
0

您可以为 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());

于 2012-05-11T10:35:44.287 回答