如何理解spring继承的问题,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
因为是子类继承父类,实例对象调用的主要是左边的父类属性和方法,所以输出结果是以左边对象为主
<bean id="sysActionService" class="com.service.impy.SysActionServiceImpy" parent="baseService" >
<property name="sysActionDao" ref="sysActionDao" />
</bean>
只需要在子类上加注解,父类上不用加会自动注入
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);
}
}
User:
package com.jeremy.spring.genericityDI;
public class User {
}
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{
}
<?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>
测试代码:
@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注解,父类的关系会被继承下来
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。