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);
}
);
}
未完待續~
