前言
-
spring是支持基于接口实现类的直接注入的;
-
支持注入map,list等集合中,不用做其他的配置,直接注入;
-
为什么要用这种方式注入bean呢?
- 适用于一个接口有多个实现类,然后根据不同的参数选择执行不同的实现类,其实就是策略模式
-
Spring 会在启动时,自动查找实现了该接口的 bean,放到这个Map中去。key为bean的名字,value为 实现了该接口的所有的 bean。
- 注意:这里只有在map的key为string类型时才有效
- @Autowired 标注作用于 Map 类型时,如果 Map 的 key 为 String 类型,则 Spring 会将容器中所有类型符合 Map 的 value 对应的类型的 Bean 增加进来,用 Bean 的 id 或 name 作为 Map 的 key。
代码实现
-
首先定义一个的接口:
package com.example.demo01.model; public interface ITest { String hello(); }
-
这个接口有多个实现类:
@Component("test1")
public class Test1 implements ITest {
@Override
public String hello() {
return "test1";
}
}
@Component("test2")
public class Test2 implements ITest {
@Override
public String hello() {
return "test2";
}
}
@Component("test3")
public class Test3 implements ITest {
@Override
public String hello() {
return "test3";
}
}
-
这里有三个实现类,都实现了
ITest
接口 -
将这三个实现类注入到sping容器中:
package com.example.demo01; import com.example.demo01.model.ITest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.Map; @SpringBootTest class Demo01ApplicationTests { @Autowired Map
testMap; @Test void contextLoads() { } @Test void testMapAutowired() { ITest test1 = testMap.get("test1"); System.out.println(test1.hello()); ITest test2 = testMap.get("test2"); System.out.println(test2.hello()); ITest test3 = testMap.get("test3"); System.out.println(test3.hello()); } } -
执行如下
文章评论