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

本文介绍如何在Spring框架中利用泛型特性进行依赖注入。通过示例展示了如何定义泛型的基类和服务类,并在子类中实现具体的泛型类型。配置Spring自动扫描组件后,演示了依赖自动装配的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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


写两个模板类:

package generic.di;

public class BaseRepository<T> {

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

写两个实现的类:

package generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User> {
	
}
package generic.di;

import org.springframework.stereotype.Service;

@Service
public 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.xsd
		http://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支持的泛型依赖注入






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值