Spring注入有继承关系的类
来源:互联网 发布:linux系统密码破解 编辑:程序博客网 时间:2024/05/01 23:56
1.通过配置文件
0<bean id="sysActionService" class="com.service.impy.SysActionServiceImpy" parent="baseService" > <property name="sysActionDao" ref="sysActionDao" /> </bean>
2.通过注解(只需要在子类上加注解,父类上不用加会自动注入)
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;@Componentpublic class UserRepository extends BaseRepository{ }
UserService:
package com.jeremy.spring.genericityDI;import org.springframework.stereotype.Service;@Servicepublic 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注解,父类的关系会被继承下来
http://www.cnblogs.com/jeremy-blog/p/4026795.html
0 0
- Spring注入有继承关系的类
- 继承关系 在spring的bean注入中的使用
- Spring的父类(继承)注入
- Spring中继承配置的注入方法
- spring bean之间的关系:继承;依赖
- Spring IOC-ApplicationContext的继承关系
- spring- bean之间的关系 继承 依赖
- Spring的注解@Qualifier小结:一个接口有两个实现类,spring注入时报错
- spring 继承的baseDao无法注入导致异常的问题
- 深入Spring Boot:Spring Context的继承关系和影响
- msxml类的继承关系
- RED类的继承关系
- UIKit类的继承关系
- unity3d 类的继承关系
- Python:类的继承关系
- spring依赖关系的管理和注入方式
- 利用反射强制转换结构相同的类(类之间无需有继承关系)
- 利用反射强制转换结构相同的类(类之间无需有继承关系)
- bzoj2140稳定婚姻
- android inflater的用法
- Eclipse打包插件Fat Jar 解压打包
- 160多个android开源代码汇总
- C++实验2-学生成绩
- Spring注入有继承关系的类
- 中缀表达式构建二叉树以及递归非递归遍历算法
- RFID系统的基本组成和原理
- Android WebView选择本地文件上传
- ActiveMQ的消息重发策略和DLQ处理
- ubantu安装xgboost
- Android之调用系统照相机并裁剪
- JVM的重排序
- applicationContext.xml详解