Spring注入有继承关系的类

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;

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

http://www.cnblogs.com/jeremy-blog/p/4026795.html

猜你喜欢

转载自m635674608.iteye.com/blog/2243589
今日推荐