微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

spring之泛型依赖注入

目录结构:

BaseRepository.java

package com.gong.spring.beans.generic.di;

public class BaseRepository<T> {

}

BaseService.java

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

class BaseService<T> {
    @Autowired
    protected BaseRepository<T> repository;
    void add() {
        System.out.println("add..");
        System.out.println(repository);
    }
}

User.java

class User {

}

UserRepository.java

 org.springframework.stereotype.Repository;

@Repository
class UserRepository extends BaseRepository<User>{

}

UserService.java

 org.springframework.stereotype.Service;

@Service(value="userService")
class UserService extends BaseService<User>{
    
}

beans-generic.di.xml

<?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.3.xsd">

    context:component-scan base-package="com.gong.spring.beans.generic.di"></context:component-scan>
</beans>

Main.java

 org.springframework.context.ApplicationContext;
 org.springframework.context.support.ClasspathXmlApplicationContext;


 Main {
    static  main(String[] args) {
        //1.创建spring的IOC容器对象
        ApplicationContext ctx = new ClasspathXmlApplicationContext("beans-generic.di.xml");
        2.从容器中获取Bean实例
        UserService userService = (UserService) ctx.getBean("userService");
        userService.add();
        
    }
}

输出

说明:所谓泛型依赖注入,就是在父类建立了引用关系,子类继承父类也会建立这种引用关系,并且真正注入的是T对应的子类类型。 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐