1. 首先, Interface1 接口有两个实现类 Interface1Impl1 和 Interface1Impl2
Interface1 接口:
package com.example.service;
/**
* Created by liuzh on 2018-05-29.
* 接口1
*/
public interface Interface1 {
void fun1();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
以下是接口的两个实现类,请注意@service注解的使用方式,这里给每个实现类标注了不同的名称,方便在@Resource注入时区别注入
Interface1 接口实现类1:
package com.example.service.impl;
import com.example.service.Interface1;
import org.springframework.stereotype.Service;
/**
* Created by liuzh on 2018-05-29.
*/
@Service("s1")
public class Interface1Impl1 implements Interface1 {
@Override
public void fun1() {
System.out.println("接口1实现类 ...");
}
public void fun2(){
System.out.println("接口1实现类1 fun2 ...");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
Interface1 接口实现类2:
package com.example.service.impl;
import com.example.service.Interface1;
import org.springframework.stereotype.Service;
/**
* Created by liuzh on 2018-05-29.
*/
@Service("s2")
public class Interface1Impl2 implements Interface1 {
@Override
public void fun1() {
System.out.println("接口1实现类 ...");
}
public void fun2(){
System.out.println("接口1实现类2 fun2 ...");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
2. 通过 @Autowired 和 @Qualifier 配合注入
@Autowired
@Qualifier("interface1Impl1")
Interface1 interface1; //正常启动
- 1
- 2
- 3
3. 使用@Resource注入,根据默认类名区分
@Resource(name = "interface1Impl1")
Interface1 interface1; //正常启动
- 1
- 2
4. 使用@Resource注入,根据@Service指定的名称区分
@Resource(name = "s1")
Interface1 interface1; //正常启动
- 1
- 2
使用@Resource注入,根据@Service指定的名称区分,可以避免多个实现类在不同包下,但是类名相同的情况。
--------------------- 本文来自 niceliusir 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/niceLiuSir/article/details/80499821?utm_source=copy