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 {

}

 

posted @ 2020-05-28 17:14  林淼零  阅读(316)  评论(0编辑  收藏  举报