【问题标题】:Spring @Service generics: Do I need to create a bean for each type?Spring @Service 泛型:我是否需要为每种类型创建一个 bean?
【发布时间】:2023-03-17 07:50:05
【问题描述】:

我正在尝试创建可用于任何类型实体的通用 crud 服务。但是当我尝试它时,我注意到即使我自动连接了几个不同的服务,例如

@Autowired
MyService<Item> itemService;

@Autowired
MyService<Students> studentsService;

当我尝试 .findAll() 方法时,我注意到它在两个服务上都返回了项目……!所以在做了一些调试之后,我注意到 itemService 和 studentsService 的实例是相同的,这可以解释我刚才提到的内容。

为了确保这一点,我做了一些小测试,如下所示:

    @Autowired
    Foo<String> fooStr;

    @Autowired
    Foo<Long> fooLong;

    static int counter = 0;

    @Service
    class Foo <T> {
        public Foo(){
            counter++;
        }
    }

    @EventListener(ApplicationReadyEvent.class)
    public void doSomethingAfterStartup() {
        System.out.println("hello world, I have just started up " + counter);
    }

基本上,我设置了一个通用的 foo 服务并在我假设应该是两个不同的实例(Foo 和 Foo)下自动装配它,并在构造函数上设置一个计数器来检查这个类被实例化的次数。但是,不是 counter = 2(一个来自 fooStr,另一个来自 fooLong),它实际上是 1,我想这证实了我之前的假设。

所以这是我的问题:如果我使用@Service,我真的需要自己为每种泛型类型声明一个bean吗?没有更简单的方法吗?我必须为一个几乎相同的项目制作很多杂物,所以我真的很想避免在可能的情况下为每个实体类型声明所有 bean

【问题讨论】:

标签: java spring spring-boot spring-data-jpa spring-data


【解决方案1】:

默认情况下Service 是一个单例。为了每次都获得一个新实例,请使用 @Scope("prototype") Service 类上的注释

【讨论】:

  • 谢谢。如果它是不同的泛型类型,是否可以保持单例但创建一个新实例,而我不必为每个泛型类型定义一个 bean?
猜你喜欢
  • 2019-02-18
  • 2018-09-03
  • 2018-06-12
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 2020-07-11
相关资源
最近更新 更多