Spring4新特性泛型依赖注入

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38409944/article/details/82688265

什么叫做泛型依赖注入呢?

就是带泛型的两个父类他们之间有引用关系,
子类各自继承他们,子类之间彼此之间也会有父类间的引用关系。

举例:
两个父类:之间有引用关系。

package one;

public class Respository<T> {
}

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

public class Service<T> {
    @Autowired
    protected Respository<T> respository;
    public void add(){
        System.out.println("Add");
        System.out.println(respository);
    }
}

随便创建个泛型实例类:

public class User {
}

两个子类继承父类:

import org.springframework.stereotype.Component;

@Component
public class UserRespository extends Respository<User> {
}

@Component
public class UserService extends Service<User> {
}

配置xml注解注入:

<context:component-scan base-package="one">
   </context:component-scan>

测试:

 public static void main(String[] args) throws SQLException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService five = (UserService) applicationContext.getBean("userService");
        five.add();
    }

输出:

Add
one.UserRespository@799d4f69

可以看到子类也继承了父类的引用关系,不过UserService中的引用类是Respository的实现类,即UserRespository类。
注意:
@Autowired注解是为了 引用关系,但是父类上不需要注解,其 实现类需要注解,交给IOC管理。

猜你喜欢

转载自blog.csdn.net/qq_38409944/article/details/82688265
今日推荐