使用@Controller获取所有带注释的控制器

有没有办法获得所有控制器的列表,这些控制器是用@Controller注释的? 我想用它们像:

 @Autowired public void addAll(List controllers) throws Exception { for (Controller controller : controllers) { ... } } 

谢谢!

getBeansWithAnnotation()

如果你用控制器注释了它们:

 @Autowired private ListableBeanFactory listableBeanFactory; 

然后

 Map controllers; controllers = listableBeanFactory.getBeansWithAnnotation(Controller.class); 
  1. 您也可以使用和BeanFactory为您完成大部分操作的事实。 @NimChimpsky给出了一个很好的例子。

  2. 您可以使用其中任何一个扫描类路径

    • AnnotationUtils.html#findAnnotationDeclaringClass
    • 或者手动使用类似下面的示例代码
 public List scanForComponents() { List components = new LinkedList(); ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class)); for (String componentBasePacke : componentBasePackages) { for (BeanDefinition bd : scanner.findCandidateComponents(componentBasePacke)) { try { components.add(Class.forName(bd.getBeanClassName())); } catch (ClassNotFoundException ex) { } } } return components; }