Spring 泛型依賴注入

Spring 4.x可以支持泛型依賴注入,也就是子類可以繼承父類的依賴,注入相應的泛型成員變量子類。


比如,有泛型基類 BaseService<T>和BaseController<T>,Controller包含Service成員,分別有Teacher和Student兩個子類,TeacherService和StudentService、TeacherController和StudentController。

1、 BaseService<T>

package com.generic.di;

public class BaseService<T> {


}

2、 BaseController<T>

package com.generic.di;

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

public class BaseController<T> {

@Autowired
protected BaseService<T> service;

public void execute() {
System.out.println("execute...");
System.out.println(service); // 此處打印出實際的子類對象
}
}

3、TeacherService

package com.generic.di.teacher;

import org.springframework.stereotype.Service;

import com.generic.di.BaseService;

@Service
public class TeacherService extends BaseService<Teacher> {

}

4、TeacherController

package com.generic.di.teacher;


import org.springframework.stereotype.Controller;


import com.generic.di.BaseController;


@Controller
public class TeacherController extends BaseController<Teacher> {


}

5、StudentService

package com.generic.di.student;


import org.springframework.stereotype.Service;


import com.generic.di.BaseService;


@Service
public class StudentService extends BaseService<Student> {


}

6、StudentController

package com.generic.di.student;


import org.springframework.stereotype.Controller;


import com.generic.di.BaseController;


@Controller
public class StudentController extends BaseController<Student> {


}

7、配置文件

<?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-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">


<context:component-scan 
base-package="com.generic">
</context:component-scan>
</beans>

8、main

public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");


StudentController studentController = (StudentController) context.getBean("studentController");
studentController.execute();

TeacherController teacherController = (TeacherController) context.getBean("teacherController");
teacherController.execute();
}
}

執行結果

execute...
com.generic.di.student.StudentService@d6da883
execute...
com.generic.di.teacher.TeacherService@45afc369

從結果可以看出,StudentController注入的是StudentSerive對象,TeacherController注入的是TeacherService對象,說明泛型基類的依賴關係,被子類自動繼承,並根據泛型找到對應的子類。

發佈了46 篇原創文章 · 獲贊 10 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章