Spring中泛型依赖注入

来源:互联网 发布:php过滤所有的空格 编辑:程序博客网 时间:2024/06/07 01:50

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> {@Autowiredprotected 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;@Repositorypublic class UserRepository extends BaseRepository<User>{}


5、UserService类

package com.at.beans.generic.di;import org.springframework.stereotype.Service;@Servicepublic 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.xsdhttp://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 点击打开链接



原创粉丝点击