ApplicationContext 应用上下文 getBeansWithAnnotation()  根据注解类型获取的对应的 bean名称bean对象

/**
 * 找到所有具有提供的{@link Annotation}类型的{@code Class}的bean,返回具有相应bean实例的bean名称映射。
 */
Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;

 

使用实例:

通过applicationContext.getBeansWithAnnotation()获取到所有拥有特定注解的Beans集合,然后遍历所有bean实现业务场景。

class TestApplicationContext implements ApplicationContextAware {

    protected ApplicationContext applicationContext;
	
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void init() throws Exception {
        //  获取Test注解的类
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(Test.class);
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            // 根据注解的属性值判断
            if (!TestSuper.class.isAssignableFrom(entry.getValue().getClass())) {
                throw new RuntimeException(entry.getKey() + " - 未继承 TestTestSuper");
            }
        }
    }
	
}

 


版权声明:本文为baidu_36327010原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/baidu_36327010/article/details/84773726