Spring中泛型依賴注入

Spring中泛型依賴注入

一、說在前面

泛型注入是Spring4.x所具有的新特性


(1)BaseService<T>:有RoleService和UserService兩的子類。
(2)BaseRepepositry<T>:有UserRepository和RoleRepositry兩個子類。
(3)由於BaseService<T>和BaseRepepositry<T>有關係,所以根據這種關係得出下面的子類也存在這樣的關係。


二、實例演示

1、BaseRepository類

package com.at.beans.generic.di;

public class BaseRepository<T> {

}


2、BaseService類

package com.at.beans.generic.di;

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

public class BaseService<T> {
	
	@Autowired
	protected BaseRepository<T> repository;
	
	public void add(){
		System.out.println("add.....");
		System.out.println(repository);
	}
}


3、User類

package com.at.beans.generic.di;

public class User {

}


4、UserRepository類

package com.at.beans.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User>{

}


5、UserService類

package com.at.beans.generic.di;

import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User>{

}


6、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.at.beans.generic.di"></context:component-scan>

</beans>

7、測試函數
package com.at.beans.generic.di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestGenericDI {

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-generic-di.xml");
		UserService userService =  (UserService) ctx.getBean("userService");
		userService.add();
	}
}


8、運行結果

六月 04, 2017 7:02:42 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4ec12ad8: startup date [Sun Jun 04 19:02:42 CST 2017]; root of context hierarchy
六月 04, 2017 7:02:43 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-generic-di.xml]
add.....
com.at.beans.generic.di.UserRepository@2e909348






By luoyepiaoxue2014

微博地址:http://weibo.com/luoyepiaoxue2014 點擊打開鏈接



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章