Spring4学习回顾之路10-Spring4.x新特性:泛型依赖注入

泛型依赖注入:Spring 4.x中可以为子类注入子类对应的泛型类型的成员变量的引用。

  话语太过抽象,直接看代码案例,依次建立如下代码:

User.java

package com.lql.spring05;

/**
 * @author: lql
 * @date: 2019.10.28
 * Description:
 */
public class User {
    
}

BaseService.java

package com.lql.spring05;

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

/**
 * @author: lql
 * @date: 2019.10.28
 * Description:
 */
public class BaseService<T> {


    @Autowired
    protected BaseRepository<T> repository;

    public void add() {
        System.out.println("进入add()方法");
        System.out.println("repository = " + repository);
    }
}

BaseRepository.java

package com.lql.spring05;

/**
 * @author: lql
 * @date: 2019.10.28
 * Description:
 * Created with IntelliJ IDEA
 */
public class BaseRepository<T> {

}

UserService.java

package com.lql.spring05;

import org.springframework.stereotype.Service;

/**
 * @author: lql
 * @date: 2019.10.28
 * Description:
 */
@Service
public class UserService extends BaseService<User> {


}

UserReposltory.java

package com.lql.spring05;

import org.springframework.stereotype.Repository;

/**
 * @author: lql
 * @date: 2019.10.28
 * Description:
 * Created with IntelliJ IDEA
 */
@Repository
public class UserRepository extends BaseRepository<User> {

}

编写配置文件

<?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.xsd">
    <context:component-scan base-package="com.lql.spring05"/>
</beans>

编写测试类

package com.lql.spring05;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author: lql
 * @date: 2019.10.28
 * Description:
 * Created with IntelliJ IDEA
 */
public class Test {
    public static void main(String[] args) {

        ApplicationContext app = new ClassPathXmlApplicationContext("spring05.xml");

        UserService userService = app.getBean("userService", UserService.class);

        userService.add();
    }
}

测试结果:

进入add()方法
repository = com.lql.spring05.UserRepository@79da8dc5

和我们预计的一样,被注入进来了,刚才写的那么多类其实可以用如下图来概括:

原文地址:https://www.cnblogs.com/-qilin/p/11754522.html