zoukankan      html  css  js  c++  java
  • spring之泛型依赖注入

    目录结构:

    BaseRepository.java

    package com.gong.spring.beans.generic.di;
    
    public class BaseRepository<T> {
    
    }

    BaseService.java

    package com.gong.spring.beans.generic.di;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    public class BaseService<T> {
        @Autowired
        protected BaseRepository<T> repository;
        public void add() {
            System.out.println("add..");
            System.out.println(repository);
        }
    }

    User.java

    package com.gong.spring.beans.generic.di;
    
    public class User {
    
    }

    UserRepository.java

    package com.gong.spring.beans.generic.di;
    
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class UserRepository extends BaseRepository<User>{
    
    }

    UserService.java

    package com.gong.spring.beans.generic.di;
    
    import org.springframework.stereotype.Service;
    
    @Service(value="userService")
    public 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

    package com.gong.spring.beans.generic.di;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    
    public class Main {
        public static void 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对应的子类类型。 

  • 相关阅读:
    [luogu T71973]卡常者π酱
    [日常] HEOI 2019 退役记
    [教程]网络流详解: 从入门到放弃
    [LOJ 6213]「美团 CodeM 决赛」radar
    [BZOJ 1568][JSOI2008]Blue Mary开公司
    [BZOJ 3167][HEOI 2013]SAO
    [BZOJ 4763]雪辉
    [LOJ 2146][BZOJ 4873][Shoi2017]寿司餐厅
    [HZNOI #koishi] Magic
    [luogu P4230]连环病原体
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12161517.html
Copyright © 2011-2022 走看看