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
- Spring框架学习(11):Spring泛型依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring 框架学习(二) 依赖注入
- Spring框架学习(二)--依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- spring框架学习(二)依赖注入
- Path&PathMeasure完全解析
- 初尝Java异步编程
- 简述值类型和引用类型的区别
- table表格的一个css代码
- Git入门
- Spring框架学习(11):Spring泛型依赖注入
- C++之智能指针总结
- JPA学习
- Mars Stomatology Gym
- mac安装git后,在终端里运行git命令,系统提示需要安装Xcode问题解决
- 数据库连接查询使用and与where区别
- 凸包初学整合
- SignalR Self Host+MVC等多端消息推送服务(1)
- 使用python获取电脑的磁盘信息