温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何理解spring继承的问题

发布时间:2021-09-24 09:32:11 来源:亿速云 阅读:129 作者:柒染 栏目:开发技术

如何理解spring继承的问题,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

spring继承的问题

如何理解spring继承的问题

如何理解spring继承的问题

为什么输出是0呢?

因为是子类继承父类,实例对象调用的主要是左边的父类属性和方法,所以输出结果是以左边对象为主

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 {
}

新建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{
}

在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>

测试代码和结果

测试代码:

@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注解,父类的关系会被继承下来

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI