java通过上下文遍历bean

来源:互联网 发布:手机捕鱼游戏源码 编辑:程序博客网 时间:2024/06/07 03:17
@Component
public class CommonServiceFactory implements ApplicationContextAware {
private static Map<String, CommonService> commonServiceMap;


@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Map<String, CommonService> map = applicationContext.getBeansOfType(CommonService.class);
commonServiceMap = new HashMap<>();
map.forEach((key, value) -> commonServiceMap.put(value.getIdentify(), value));
}


@SuppressWarnings("unchecked")
public static <T extends CommonService> T getCommonService(String code) {
return (T) commonServiceMap.get(code);
}


}