How to scan classes for annotations?

前端 未结 7 2195
野性不改
野性不改 2020-12-28 17:00

I have a plain jane servlets web application, and some of my classes have the following annotations:

@Controller
@RequestMapping(name = \"/blog/\")
public cl         


        
7条回答
  •  天命终不由人
    2020-12-28 17:52

    The following code worked for me, the below example uses Java 11 and spring ClassPathScanningCandidateComponentProvider. The usage is to find all classes annotated with @XmlRootElement

    public static void main(String[] args) throws ClassNotFoundException {
        var scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(XmlRootElement.class));
    
        //you can loop here, for multiple packages
        var beans = scanner.findCandidateComponents("com.example");
        for (var bean : beans) {
            var className = bean.getBeanClassName();
            Class clazz = Class.forName(className);
            //creates initial JAXBContext for later usage
            //JaxbContextMapper.get(clazz);
            System.out.println(clazz.getName());
        }
    }
    

提交回复
热议问题