spring中可以通过getBeansWithAnnotation来获取ioc容器中使用了某个注解的所有bean,这个方法底层原理:我们知道可以通过反射来获取一个类中所有的注解,然后通过遍历spring容器中所有bean就能获取需要的结果。

//自定义@Auditable注解
package com.yk.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface Auditable {
    String[] value();
}

//在person类中我们引入@Auditable,并通过@Component将其注入spring容器
package com.yk.annotation;

import org.springframework.stereotype.Component;

@Component
@Auditable("person.sleep")
public class Person {

    void sleep(){
        System.out.println("睡觉了");
    }
}

    @Test
    public void test03() throws ClassNotFoundException {
        Class aClass = Class.forName("com.yk.annotation.Auditable");
        //boolean b = aClass.isAnnotation();
        //System.out.println(b);
        //Person person = ac.getBean(Person.class);
        Map beansWithAnnotation = ac.getBeansWithAnnotation(aClass);

        Iterator entries = beansWithAnnotation.entrySet().iterator();

        while (entries.hasNext()) {

            Map.Entry entry = (Map.Entry) entries.next();
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

        }
    }

打印结果为
在这里插入图片描述

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐