Spring的接口集合注入功能


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();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM