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