zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Spring的接口集合注入功能

2023-03-07 09:38:30 时间

Spring的接口集合注入功能

对于Spring中已经注入的bean, 可以使用Autowired, 通过Map<String, BeanInterface>List<BeanInterface>的方式直接注入

实现步骤

  1. 定义一个接口
  2. 实现这个接口的一系列类, 都加上 @Component 或者 @Service 注解, 使其成为 spring bean
  3. 在其他类中, 通过 @Autowired private Map<String, InterfaceName> interfaceMap;@Autowired private List<InterfaceName> interfaceList;可以得到上面定义的类的bean映射或列表
    • 对于Map, Spring会将实例化的bean放入value, key则为bean的名称
    • 对于List,列表就是实例化的bean
  4. 如果要控制list中的顺序, 在实现类中加入@Order(value) 注解, 值越小越先被初始化越先被放入List

验证

先定义一个接口

public interface GenericService {
    void breath();
}

然后定义接口的实现类

// Dog.java
@Service("dog-control")
public class Dog implements GenericService {
    @Override
    public void breath() {
        System.out.println("dog breath");
    }
}

//Cat.java
@Component
public class Cat implements GenericService {
    @Override
    public void breath() {
        System.out.println("cat breath");
    }
}

在Demo类中引用

@Component
public class Demo {

    @Autowired
    private Map<String,GenericService> GenericServiceMap;

    @Autowired
    private List<GenericService> GenericServiceList;

    public void dogBreath() {
        this.GenericServiceMap.get("dog-control").breath();
    }

    public void firstBreath() {
        this.GenericServiceList.get(0).breath();
    }
}

测试用例

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {

    @Autowired
    private com.service.Demo demo;

    @Test
    public  void testMap(){
        demo.dogBreath();
    }

    @Test
    public  void testList(){
        demo.firstBreath();
    }
}