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

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

BaseRepository

package com.beans.generic.di;

public class BaseRepository<T> {
         
}

BaseService

package com.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);
       }
       
}



UserRepository

package com.beans.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User>{
        
}

UserService

package com.beans.generic.di;

import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User>{
       
}

配置文件xml

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

</beans>

运行主类:

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

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

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

猜你喜欢

转载自blog.csdn.net/qq_37774171/article/details/85489050