Java annotation scanning with spring

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 12:09:34

Just get the annotation object and pull out the value

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;

Let me know if that's not clear.

user6690034

In my case I wrote like below:

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);
}

Maybe you can use http://scannotation.sourceforge.net/ framework to achive that.

Hope it helps.

You can provide a custom BeanNameGenerator to the ClassPathBeanDefinitionScanner, which can look for the value of your annotation and return that as the bean name.

I think an implementation along these lines should work for you.

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");
    }
}

Add this to your previous scanner code: scanner.setBeanNameGenerator(new CustomBeanNameGenerator());

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!