@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);
}
}
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);
}
}
本文介绍了一个使用Spring框架实现依赖注入的示例代码。通过@Component注解定义了一个名为CommonServiceFactory的服务工厂类,并实现了ApplicationContextAware接口来获取Spring上下文中的所有CommonService实例。该类还提供了一个静态方法getCommonService,用于根据给定的代码获取相应的CommonService实例。
5万+

被折叠的 条评论
为什么被折叠?



