Spring 依赖搜索即在开发过程中通过 Spring的依赖注入机制,对所需求的Bean进行查找。
下面通过一个例子来学习一下。
首先定义一个接口
public interface HelloService {
void sayHello();
}
然后接口有两个实现,并通过@Component 注解实例化到Spring容器中
@Component
public class TomHelloServiceImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("Hello Tom");
}
}
@Component
public class JerryHelloServiceImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("Hello Jerry");
}
}
在控制器中注入
@RestController
public class HelloController {
//注入全部的 HelloService 接口的实现
@Autowired
List<HelloService> helloServiceList;
//注入Bean的名字为 jerryHelloServiceImpl 的HelloService 接口的实现
@Autowired
HelloService jerryHelloServiceImpl;
//key为Bean的名字
@Autowired
Map<String, HelloService> helloServiceMap;
@GetMapping("/hello")
public void HelloController(){
for (HelloService helloService : helloServiceList) {
helloService.sayHello();
}
//遍历map
Set<Map.Entry<String,HelloService>> entrySet = helloServiceMap.entrySet();
Iterator<Map.Entry<String, HelloService>> it2 = entrySet.iterator();
while(it2.hasNext()){
Map.Entry<String, HelloService> entry = it2.next();
String key = entry.getKey();
HelloService helloService = entry.getValue();
System.out.println(key+": "+helloService);
}
//依赖搜索
HelloService tom = helloServiceMap.get("tomHelloServiceImpl");
tom.sayHello();
}
输出日志
Hello Jerry
Hello Tom
jerryHelloServiceImpl: com.springboot.security02.service.JerryHelloServiceImpl@9f46d94
tomHelloServiceImpl: com.springboot.security02.service.TomHelloServiceImpl@18cc679e
Hello Tom
Hello Jerry
从输出日志我们可以看到,通过@Autowired 注解,如果指定了Bean的名字,则会注入该Bena,没有指定的话 Spring 会把所有HelloService接口的实现全部注入进来,如果注入到 Map 中的话,则 key是Bean的名字,value是Bean实例。