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

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

    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:p="http://www.springframework.org/schema/p"
        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.aff.spring.beans.generic.di"></context:component-scan>
    </beans>

    Main

    package com.aff.spring.beans.generic.di;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Main {
    
        public static void main(String[] args) {
             ApplicationContext  ctx = new ClassPathXmlApplicationContext("beans-generic-di.xml");
             
             UserService userService =  (UserService) ctx.getBean("userService");
             userService.add();
             //add..
             //com.aff.spring.beans.generic.di.UserRepository@3234e239
    
        }
    }

    BaseRepository.java

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

    BaseService.java

    package com.aff.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);
        }
    }

     UserRepository.java

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

    UserService.java

    package com.aff.spring.beans.generic.di;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserService extends BaseService<User> {
    
    }

    User

    package com.aff.spring.beans.generic.di;
    
    public class User {
    
    }
    All that work will definitely pay off
  • 相关阅读:
    属性,类方法,静态方法,Python2和3方法
    类的继承
    面向对象空间和组合
    面向对象
    内置函数和匿名函数
    一个有点意思的习题
    APUE学习笔记——10.18 system函数 与waitpid
    Linux服务器静态路由配置
    APUE学习笔记——11 线程同步、互斥锁、自旋锁、条件变量
    APUE学习笔记——11 线程基础
  • 原文地址:https://www.cnblogs.com/afangfang/p/12982117.html
Copyright © 2011-2022 走看看