1. 程式人生 > >spring學習筆記(14)——泛型依賴注入

spring學習筆記(14)——泛型依賴注入

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

                       

泛型依賴注入

spring 4.x以上版本才有

寫一個baseRepository,可以將DAO層相同的操作給封裝起來,比如一般的增刪改查,所有的DAO一般都有這些操作,因此可以寫到父類中,並且使用泛型

package com.zj.generic;public class BaseRepository<T> {    public void add() {        System.out.println("reponsitory add ....");    }}
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

baseService

package com.zj.generic;import org.springframework.beans.factory.annotation.Autowired;public
class BaseService<T> {    @Autowired    private BaseRepository<T> repository;    public void add(){        repository.add();    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
 

在BaseService中裝配了BaseRepository

寫兩個子類分別繼承他們兩

package com.zj.generic;import org.springframework.stereotype.Repository;@Repositorypublic class UserReponsitory extends BaseRepository<User>{}
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
package com.zj.generic;import org.springframework.stereotype.Service;@Servicepublic class UserService extends BaseService<User>{}
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

配置檔案配置掃描包

<?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.zj.generic"></context:component-scan></beans>
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

測試方法

package com.zj.generic;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {    public static void main(String[] args) {        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-generic.xml");        UserService userService = (UserService) ctx.getBean("userService");        userService.add();    }}
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
 
     
  • 在以上的程式碼中,BaseService中引用了BaseReponsitory,並且在BaseService的add方法中呼叫了BaseReponsitory的add方法
  •  
  • 在他們的子類中,繼承了這種關係,因此我們在測試方法中呼叫userService.add(); 也是可以成功地呼叫UserReponsitory中的add方法
  •  
  • 根據泛型T自動注入相應的Reponsitory
  •  
           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述