Spring的泛型依賴注入


Spring 4.x 中可以為子類注入子類對應的泛型類型的成員變量的引用,(這樣子類和子類對應的泛型類自動建立關系)
具體說明:
泛型注入:就是Bean1和Bean2注入了泛型,並且Bean1和Bean2建立依賴關系,這樣子類Bean3(繼承bean1)和bean4(繼承bean2)就會自動建立關系
不是泛型注入:就是說Bean1和Bean2都沒有注入泛型,只是建立了關系,子類Bean3(繼承bean1)和bean4(繼承bean2)也會自動建立關系

泛型依賴注入的實現步驟:
  1新建兩個泛型類,並建立依賴關系:
  具體代碼:
  BaseRepository:

package com.jeremy.spring.genericityDI;
public class BaseRepository{
}

  BaseService:

package com.jeremy.spring.genericityDI;

import org.springframework.beans.factory.annotation.Autowired;

public class BaseService<T> {
    
    @Autowired------//這里告訴IOC容器自動裝配有依賴關系的Bean protected BaseRepository baseRepository;--------//這里是子類繼承依賴關系
    public void add(){
        System.out.println("add..............");
        System.out.println(baseRepository);
    }
}

  2新建一個泛型類:

  User:

package com.jeremy.spring.genericityDI;

public class User {

}

  3新建BaseRepository和BaseService的子類
  UserRepository:

package com.jeremy.spring.genericityDI;
import org.springframework.stereotype.Component;

@Component
public class UserRepository extends BaseRepository{
    
}

  UserService:

package com.jeremy.spring.genericityDI;

import org.springframework.stereotype.Service;


@Service
public class UserService extends BaseService{

}

  4:在Spring的配置文件中配置自動裝配帶有注解的Bean:
  

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.jeremy.spring.genericityDI"></context:component-scan>

</beans>

5測試代碼和結果
  測試代碼:

@Test
    public void test() {
        ApplicationContext actx=new ClassPathXmlApplicationContext("Bean-genericity-di.xml");
        UserService userService=(UserService) actx.getBean("userService");
        userService.add();
    }

測試結果:

add..............
com.jeremy.spring.genericityDI.UserRepository@16546ef

從結果看,雖然子類沒有建立依賴關系,但userRepository實例還是被實例化了,就證明了父類的依賴關系,子類是可以繼承的

其實這里也可以說明,就算父類不是被IOC容器管理,但是建立關系時添加了@Autowired注解,父類的關系會被繼承下來

 

 

題外話:
那泛型注入和不是泛型注入有什么優缺點???二者真正的作用是什么呢??
至於兩種不同的方式注入到底有什么優缺點,以后自己在開發中慢慢領悟吧,現在就是把基礎弄好


免責聲明!

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



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