Spring的泛型依赖注入

Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用,(这样子类和子类对应的泛型类自动建立关系)
具体说明:
泛型注入:就是Bean1和Bean2注入了泛型,并且Bean1和Bean2建立依赖关系,这样子类Bean3(继承bean1)和bean4(继承bean2)就会自动建立关系
不是泛型注入:就是说Bean1和Bean2都没有注入泛型,只是建立了关系,子类Bean3(继承bean1)和bean4(继承bean2)也会自动建立关系

泛型依赖注入的实现步骤:
  1新建两个泛型类,并建立依赖关系:
  具体代码:
  BaseRepository:

package com.jeremy.spring.genericityDI;
public class BaseRepository{
}

  BaseService:

package com.jeremy.spring.genericityDI;

import org.springframework.beans.factory.annotation.Autowired;

public class BaseService<T> {
    
    @Autowired------//这里告诉IOC容器自动装配有依赖关系的Bean
    protected BaseRepository baseRepository;--------//这里是子类继承依赖关系
    public void add(){
        System.out.println("add..............");
        System.out.println(baseRepository);
    }
}

  2新建一个泛型类:

  User:

package com.jeremy.spring.genericityDI;

public class User {

}

  3新建BaseRepository和BaseService的子类
  UserRepository:

package com.jeremy.spring.genericityDI;
import org.springframework.stereotype.Component;

@Component
public class UserRepository extends BaseRepository{
    
}

  UserService:

package com.jeremy.spring.genericityDI;

import org.springframework.stereotype.Service;


@Service
public class UserService extends BaseService{

}

  4:在Spring的配置文件中配置自动装配带有注解的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.0.xsd">
<context:component-scan base-package="com.jeremy.spring.genericityDI"></context:component-scan>

</beans>

5测试代码和结果
  测试代码:

@Test
    public void test() {
        ApplicationContext actx=new ClassPathXmlApplicationContext("Bean-genericity-di.xml");
        UserService userService=(UserService) actx.getBean("userService");
        userService.add();
    }

测试结果:

add..............
com.jeremy.spring.genericityDI.UserRepository@16546ef

从结果看,虽然子类没有建立依赖关系,但userRepository实例还是被实例化了,就证明了父类的依赖关系,子类是可以继承的

其实这里也可以说明,就算父类不是被IOC容器管理,但是建立关系时添加了@Autowired注解,父类的关系会被继承下来

 

 

题外话:
那泛型注入和不是泛型注入有什么优缺点???二者真正的作用是什么呢??
至于两种不同的方式注入到底有什么优缺点,以后自己在开发中慢慢领悟吧,现在就是把基础弄好

转载于:https://www.cnblogs.com/jeremy-blog/p/4026795.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值