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


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);
      }

  );
}
未完待续~

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM