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
  • 相关阅读:
    Ext.Net多表头跨行跨列
    操作文件
    HighMaps
    HighCharts动态读取显示
    SAP CRM 项目笔记(一) SOW(工作说明书)讨论
    .net 动态编译解决考勤计算问题
    CPU的大小端模式
    将一个数转化为任意进制的数
    关于内存对齐
    常量指针与指针常量
  • 原文地址:https://www.cnblogs.com/afangfang/p/12982117.html
Copyright © 2011-2022 走看看