Spring框架学习(11):Spring泛型依赖注入

来源:互联网 发布:在手机淘宝怎么删评价 编辑:程序博客网 时间:2024/05/18 18:03

在Spring 4.x中可以为子类注入子类对应的泛型类型的成员变量的引用

用一个简单的例子说明这个用法:


写两个模板类:

package generic.di;public class BaseRepository<T> {}
package 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);}}
如上所示,在模板类中使用autowire使BaseService依赖于BaseRepository,这个依赖会被继承

写两个实现的类:

package generic.di;import org.springframework.stereotype.Repository;@Repositorypublic class UserRepository extends BaseRepository<User> {}
package generic.di;import org.springframework.stereotype.Service;@Servicepublic class UserService extends BaseService<User>  {}
User类是个随意的类,在这里它是空的。

在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.3.xsd"><context:component-scan base-package="generic.di"></context:component-scan></beans>

用main函数测试一下,可以看到运行正常

package generic.di;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {ApplicationContext ctxt = new ClassPathXmlApplicationContext("beans-generic.xml");UserService userService = (UserService)ctxt.getBean("userService");userService.add();}}
以上就是Spring支持的泛型依赖注入






0 0
原创粉丝点击