Spring--泛型依赖注入

迷南。 2022-04-13 06:12 268阅读 0赞

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

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dhbmdqaWFuNTMw_size_16_color_FFFFFF_t_70

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

User:

  1. package com.primary.spring.beans.generic.di;
  2. public class User {
  3. }
  • BaseRepository

    1. package com.primary.spring.beans.generic.di;
    2. public class BaseRepository <T> {
    3. public void save() {
    4. System.out.println("BaseRepository save...");
    5. }
    6. }
  • BaseService

    1. package com.primary.spring.beans.generic.di;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. public class BaseService <T> {
    4. @Autowired
    5. protected BaseRepository<T> repository;
    6. public void add() {
    7. repository.save();
    8. }
    9. }
  • UserRepository

    1. package com.primary.spring.beans.generic.di;
    2. import org.springframework.stereotype.Repository;
    3. @Repository
    4. public class UserRepository extends BaseRepository<User> {
    5. public void save() {
    6. System.out.println("UserRepository save...");
    7. }
    8. }
  • UserService

    1. package com.primary.spring.beans.generic.di;
    2. import org.springframework.stereotype.Service;
    3. @Service
    4. public class UserService extends BaseService<User> {
    5. }

    测试:

  • package com.primary.spring.beans.generic.di;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    public class Main {

    1. public static void main(String[] args) {
    2. ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-generic-di.xml");
    3. UserService userService = (UserService)ctx.getBean("userService");
    4. userService.add();
    5. }

    }

    beans-generic-di.xml:

  • <?xml version=”1.0” encoding=”UTF-8”?>




    结果:

  • watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dhbmdqaWFuNTMw_size_16_color_FFFFFF_t_70 1
  • 在以上的代码中,BaseService中引用了BaseReponsitory,并且在BaseService的add方法中调用了BaseReponsitory的save方法;而在他们的子类中,继承了这种关系,因此我们在测试方法中调用userService.add(); 也是可以成功UserReponsitory中的save方法而不是BaseReponsitory的save方法。
    根据泛型T自动注入相应的Reponsitory实际应用中我们可以把经常使用到的增删改查等通用的操作些在base类中,简化代码。

发表评论

表情:
评论列表 (有 0 条评论,268人围观)

还没有评论,来说两句吧...

相关阅读

    相关 依赖注入

    纸上得来终觉浅 关于泛型依赖注入,只明白它的思想,考虑了整个下午都不明确它所应用的场合,暂时把用法记下来,后面再学习整理。使用示例如下: public class

    相关 Spring--依赖注入

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