一个接口两个实现类。
接口代码:
调用:
一、@resource
1、名字瞎写:
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.xxx.comm.service.TestHHHHUUUU' available: expected single matching bean but found 2: t1,t2
2、resource的变量名为t1。或者t2。
3、变量名为实现类的名字:
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.xxx.comm.service.TestHHHHUUUU' available: expected single matching bean but found 2: t1,t2
4、实现类不写类似的t1、t2。变量名为实现类名字
5、指定name、type就不测试了。
二、@Autowired
差不多,多个实现类的时候也是byName注入。或者使用@Qualifier指定哪一个实现类
如 https://blog.csdn.net/yangjiachang1203/article/details/52128830
三、使用工厂模式
工厂模式描述:提供一个用于创建对象的接口(工厂接口),让其实现类(工厂实现类)决定实例化哪一个类(产品类),并且由该实现类创建对应类的实例。
代码:
package com.xxx.qlms.register;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.xxx.qlms.form.api.Ifields;
@Service("FieldRegister")
public class FieldRegister implements InitializingBean, ApplicationContextAware {
Map<Integer, Ifields> serviceImplMap = new HashMap<Integer, Ifields>();
@Autowired
ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
this.applicationContext = arg0;
}
@Override
public void afterPropertiesSet() throws Exception {
Map<String, Ifields> serviceMap =
applicationContext.getBeansOfType(Ifields.class);
for (String keys : serviceMap.keySet()) {
try{
Integer index=Integer.valueOf( keys.substring(keys.indexOf(":")+1));
serviceImplMap.put( index, serviceMap.get(keys));
}catch (Exception e){
System.err.println("错误");
}
}
}
public Ifields getField(int type) {
return serviceImplMap.get(type);
}
}
解析:service代码:注解需要这样写:@Service("commonTextField:1")、@Service("AutoNumberText:15")等。注解后面的数字在调用时传过来,以表示调用的哪一个实现类。
实现两个接口会自动注入。
取出某个(如:" : ")字符后的字符串:keys.substring(keys.indexOf(":")+1)
将字符串型的数字转换成int型:Integer.valueOf("4679883")
applicationContext.getBeansOfType()方法用来获取接口的所有实现的方法。