首页 > 解决方案 > 如何在你的 spring 项目中计算所有具有 @Controllers 属性的类

问题描述

有一次面试官问我这个问题,我也答不上来。我也在谷歌上搜索过,但我没有得到任何正确的答案。

标签: javaspringhibernatespring-mvc

解决方案


请尝试下面给定的代码。

Map<String,Object> beans = ctx.getBeansWithAnnotation(Controller.class);
System.out.println(beans.size());

或者你可以用反射库试试这个。下面给出的片段可以在整个项目中搜索。

maven依赖:

org.reflections 反射 0.9.10

import org.reflections.Reflections;

public class FindAnnotation {


public static void main(String[] args) {
    System.out.println("Scanning using Reflections:");

    Reflections ref = new Reflections("com.some.package");
    for (Class<?> cl : ref.getTypesAnnotatedWith(Controller.class)) {
        //count
    }
}}

推荐阅读