在我们平时的系统开发中可能会一个接口有多是实现的情况存在,现在有两种实现方式
方式一:
@Autowired 配合 @Qualifier("类别名")一起使用
方式二:
使用@Resource(name = "类别名") 指定类的别名
测试代码
1. 接口
/**
* 注入测试接口
* @author: clx
* @date: 2019/7/23
* @version: 1.1.0
*/
public interface AutoTestService {
String getString();
}
2。 实现
实现1
import com.example.javautilsproject.service.AutoTestService;
import org.springframework.stereotype.Service;
/**
* 注入实现类 1
* @author: clx
* @date: 2019/7/23
* @version: 1.1.0
*/
@Service("autoTestService1")
public class AutoTestService1Impl implements AutoTestService {
@Override
public String getString() {
return "方式[1]调用成功";
}
}
实现2
import com.example.javautilsproject.service.AutoTestService;
import org.springframework.stereotype.Service;
/**
* @author: clx
* @date: 2019/7/23
* @version: 1.1.0
*/
@Service("autoTestService2")
public class AutoTestService2Impl implements AutoTestService {
@Override
public String getString() {
return "方式[2]调用成功";
}
}
3. 测试类
import com.example.javautilsproject.service.AutoTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author: clx
* @date: 2019/7/23
* @version: 1.1.0
*/
@RestController
public class TestController {
@Autowired
@Qualifier("autoTestService1")
private AutoTestService autoTestService1;
@Autowired
@Qualifier("autoTestService2")
private AutoTestService autoTestService2;
@Resource(name = "autoTestService1")
private AutoTestService resourceAutoTestService1;
@Resource(name = "autoTestService2")
private AutoTestService resourceAutoTestService2;
@GetMapping("autoTest")
public void autoTest() {
String autowired1 = autoTestService1.getString();
String autowired2 = autoTestService2.getString();
String resource1 = resourceAutoTestService1.getString();
String resource2 = resourceAutoTestService2.getString();
System.out.println("Qualifier----" + autowired1);
System.out.println("Qualifier----" + autowired2);
System.out.println("Resource----" + resource1);
System.out.println("Resource----" + resource2);
}
}
4. 测试结构