// 接口
public interface ServiceInterface {
public void method();
}
// 具体两个实现类
@Service("aService")
public class AServiceImpl implements ServiceInterface {
@Override
public void method() {
System.out.println("the impl is A");
}
@Override
public String toString() {
return "A";
}
}
@Service("bService")
public class BServiceImpl implements ServiceInterface {
@Override
public void method() {
System.out.println("the impl is B");
}
@Override
public String toString() {
return "B";
}
}
@Service("register")
public class Register implements InitializingBean, ApplicationContextAware {
private Map<String, ServiceInterface> serviceImplMap = new HashMap<>();
private ApplicationContext applicationContext;
// 获取spring的上下文
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
// 获取接口实现类的所有bean,并按自己定的规则放入map中
@Override
public void afterPropertiesSet() throws Exception {
Map<String, ServiceInterface> beanMap = applicationContext.getBeansOfType(ServiceInterface.class);
// 以下代码是将bean按照自己定的规则放入map中,这里我的规则是key:service.toString();value:bean
// 调用时,参数传入service.toString()的具体字符串就能获取到相应的bean
// 此处也可以不做以下的操作,直接使用beanMap,在调用时,传入bean的名称
for (ServiceInterface serviceImpl : beanMap.values()) {
serviceImplMap.put(serviceImpl.toString(), serviceImpl);
}
}
public ServiceInterface getServiceImpl(String name) {
return serviceImplMap.get(name);
}
}
@Resource
Register register;
@Test
public void testService() {
ServiceInterface service = register.getServiceImpl("A");
service.method();
ServiceInterface service2 = register.getServiceImpl("B");
service2.method();
}
@Component("informerRegistry")
public final class InformerRegistry implements ApplicationContextAware{
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有