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
  • 相关阅读:
    Amazon后台登陆以及跟卖
    python图像识别--验证码
    python selenium下载电子书
    Amazon后台模拟登陆
    python简单粗暴多进程之concurrent.futures
    SmartDo数据挖掘思路
    python3倒叙字符串
    Effective C++ —— 构造/析构/赋值运算(二)
    Effective C++ —— 让自己习惯C++(一)
    cocos2dx-3.x物理引擎Box2D介绍
  • 原文地址:https://www.cnblogs.com/afangfang/p/12982117.html
Copyright © 2011-2022 走看看