Java annotation scanning with spring

后端 未结 4 1470
Happy的楠姐
Happy的楠姐 2021-01-07 04:37

I have few classes that I need to annotate with a name so I defined my annotation as

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @i         


        
相关标签:
4条回答
  • 2021-01-07 05:03

    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.

    0 讨论(0)
  • 2021-01-07 05:03

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

    Hope it helps.

    0 讨论(0)
  • 2021-01-07 05:07

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

    0 讨论(0)
  • 2021-01-07 05:14

    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);
    }
    
    0 讨论(0)
提交回复
热议问题