1、一个实现类实现多个接口
例如:serviceImpl implements Interface1,Interface2
在controller中
@Autowired Interface1
只能调用 Interface1接口的方法
总结,注入单个接口,只能调用对应的接口方法
2、一个接口多个实现类,注入指定的实现类
例如:Interface 接口有两个实现类 InterfaceImpl1 和 InterfaceImpl2
//实现类1
@Service
public class InterfaceImpl1 implements Interface {
//实现类1
@Service
public class InterfaceImpl2implements Interface {
//业务类,controller
@Autowired Interface
private Interface interface;
按照上面的写法,启动服务时会报错
解决方法
1.指明实现类的优先级,注入的时候使用优先级高的实现类
//实现类1
@Service
@Primary //同一个接口的实现类,最多只能有一个添加该注解
public class InterfaceImpl1 implements Interface {
在controller中注入接口,默认使用的是Primary 标注的实现类的方法
2.通过 @Autowired 和 @Qualifier 配合注入
@Autowired
@Qualifier("interfaceImpl1")
Interface1 interface1; //正常启动
3.使用@Resource注入,根据默认类名区分
@Resource(name = "interfaceImpl1")
Interface1 interface1; //正常启动
4.使用@Resource注入,根据@Service指定的名称区分
需要在实现类@Service后设置名称:
@Service("s1")
public class InterfaceImpl1 implements Interface {
@Resource(name = "s1")
Interface1 interface1; //正常启动
spring常用注解说明
- @Configuration把一个类作为一个IoC容器,它的某个方法头上如果注册了@Bean,就会作为这个Spring容器中的Bean。
- @Scope注解 作用域
- @Lazy(true) 表示延迟初始化
- @Service用于标注业务层组件、
- @Controller用于标注控制层组件(如struts中的action)
- @Repository用于标注数据访问组件,即DAO组件。
- @Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
- @Scope用于指定scope作用域的(用在类上)
- @PostConstruct用于指定初始化方法(用在方法上)
- @PreDestory用于指定销毁方法(用在方法上)
- @Resource 默认按名称装配,当找不到与名称匹配的bean才会按类型装配。
- @DependsOn:定义Bean初始化及销毁时的顺序
- @Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
- @Autowired 默认按类型装配,如果我们想使用按名称装配,可以结合@Qualifier注解一起使用
- @Autowired @Qualifier("personDaoBean") 存在多个实例配合使用