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