首页 > 编程语言 > 详细

Spring通过注解获取所有被注解标注的Beans

时间:2019-11-15 15:33:15      阅读:338      评论:0      收藏:0      [点我收藏+]

Spring提供的方法:Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;

1,作用:Find all beans whose Class has the supplied Annotation type. 

    找到所有拥有annotationType注解的bean;

2,参数:annotationType - the type of annotation to look for:

    需要获得的bean的注解类型。

3,Returns: a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values。

    返回一个被注解表示的bean的Map对象,bean的names作为key,与name对应的实例做为值

4. Throws: BeansException - if a bean could not be created、 

    如果bean不能被创建,抛出beanException!

 

遍历所有bean:

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(MsgTypeHandler.class);
    MessageServiceContext messageServiceContext = event.getApplicationContext().getBean(MessageServiceContext.class);
    beans.forEach((name, bean) -> {
        MsgTypeHandler typeHandler = bean.getClass().getAnnotation(MsgTypeHandler.class);
        messageServiceContext.putMessageService(typeHandler.value().code, (MessageService) bean);
      }

  );
}
未完待续~

Spring通过注解获取所有被注解标注的Beans

原文:https://www.cnblogs.com/unknownCode/p/11866284.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!