spring基础知识 (16):泛型依赖注入

泛型依赖注入

spring 4.x以上版本才有
创建两个带泛型的类,并配置两者的依赖关系,对于继承这两个类的子类,如果泛型相同,则会继承这种依赖关系:
这里写图片描述

如上图:
定义了两个泛型base类:BaseService和BaseRepository
对于UserService和UserRpository分别继承两个base类,泛型都是User,则他们俩继承了父类的依赖关系。

  • BaseRepository
package com.spring.generic.di;

public class BaseRepository<T> {

    public void save(){
        System.out.println("BaseRepository save...");
    }
}
  • BaseService
package com.spring.generic.di;

import org.springframework.beans.factory.annotation.Autowired;

public class BaseService<T> {

    @Autowired
    private BaseRepository<T> repository;

    public void save(){
        repository.save();
    }
}

  • UserRepository
package com.spring.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User> {

    public void save(){
        System.out.println("UserRepository save...");
    }
}
  • UserService
package com.spring.generic.di;

import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User> {

}

测试:

package com.spring.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.save();
    }
}

这里写图片描述

  • 在以上的代码中,BaseService中引用了BaseReponsitory,并且在BaseService的add方法中调用了BaseReponsitory的add方法
  • 在他们的子类中,继承了这种关系,因此我们在测试方法中调用userService.add(); 也是可以成功地调用UserReponsitory中的add方法而不是BaseReponsitory的add方法。
  • 根据泛型T自动注入相应的Reponsitory

实际应用中我们可以把经常使用到的增删改查等通用的操作些在base类中,简化代码。

猜你喜欢

转载自blog.csdn.net/abc997995674/article/details/80294397
今日推荐