spring(学习记录)泛型依赖注入

我会带着你远行 2022-04-01 19:42 312阅读 0赞

泛型依赖注入
spring 4.x以上版本才有
创建两个带泛型的类,并配置两者的依赖关系,对于继承这两个类的子类,如果泛型相同,则会继承这种依赖关系:
在这里插入图片描述
定义了两个泛型base类:BaseService和BaseRepository
对于UserService和UserRpository分别继承两个base类,泛型都是User,则他们俩继承了父类的依赖关系。

BaseRepository

  1. package com.beans.generic.di;
  2. public class BaseRepository<T> {
  3. }

BaseService

  1. package com.beans.generic.di;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. public class BaseService<T> {
  4. @Autowired
  5. protected BaseRepository<T> repository;
  6. public void add() {
  7. System.out.println("add....");
  8. System.out.println(repository);
  9. }
  10. }

UserRepository

  1. package com.beans.generic.di;
  2. import org.springframework.stereotype.Repository;
  3. @Repository
  4. public class UserRepository extends BaseRepository<User>{
  5. }

UserService

  1. package com.beans.generic.di;
  2. import org.springframework.stereotype.Service;
  3. @Service
  4. public class UserService extends BaseService<User>{
  5. }

配置文件xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  7. <context:component-scan base-package="com.beans.generic.di"></context:component-scan>
  8. </beans>

运行主类:

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

在以上的代码中,BaseService中引用了BaseReponsitory,并且在BaseService的add方法中调用了BaseReponsitory的方法
在他们的子类中,继承了这种关系,因此我们在测试方法中调用userService.add(); 也是可以成功地调用UserReponsitory中的add方法而不是BaseReponsitory的add方法。
根据泛型T自动注入相应的Reponsitory

在使用spring进行依赖注入的同时,利用泛型的优点对代码进行精简,将可重复使用的代码全部放到一个类之中,方便以后的维护和修改。同时在不增加代码的情况下增加代码的复用性。

发表评论

表情:
评论列表 (有 0 条评论,312人围观)

还没有评论,来说两句吧...

相关阅读

    相关 依赖注入

    纸上得来终觉浅 关于泛型依赖注入,只明白它的思想,考虑了整个下午都不明确它所应用的场合,暂时把用法记下来,后面再学习整理。使用示例如下: public class

    相关 Spring--依赖注入

    spring 4.x以上版本才有 创建两个带泛型的类,并配置两者的依赖关系,对于继承这两个类的子类,如果泛型相同,则会继承这种依赖关系: ![watermark_type