简体   繁体   English

注入通用服务bean

[英]Inject generic service bean

I have some highly repetitive code that i decided to move into an abstract class, for the sake of simplicity let's assume that the class looks like: 我有一些高度重复的代码,我决定进入一个抽象类,为简单起见,让我们假设该类看起来像:

class AbstractEntityService<E extends MyEntity, REPO extends MyRepository<E>> {

      @Autowired
      private REPO repo;

      ... // methods

}

and I have about 10 separate classes that need this functionality so i have 而且我有大约10个单独的类需要此功能,所以我有

@Service
class MyService1 extends AbstractEntityService<MyEntity1, MyEntity1Repo> {}

@Service
class MyService2 extends AbstractEntityService<MyEntity2, MyEntity2Repo> {}

...

MyService1 ... MyService10 don't really do anything other than to cement the types for spring's autodetection to work. MyService1 ... MyService10除了巩固用于弹簧自动检测的类型之外,实际上并没有做任何其他事情。

I'm wondering if i can get away without defining them and injecting 我想知道我是否可以不定义它们并注入

@Autowired
private AbstractEntityService<MyEntity2, MyEntity2Repo> myEntity2Repo;

directly without defining the classes myself. 直接定义自己的类。

No, I'm pretty sure you cannot. 不,我敢肯定你不能。

I think the best you can do is if you create the beans yourself in a config file. 我认为最好的方法是在配置文件中自行创建bean。

import javax.inject.Inject; 
import org.springframework.context.annotation.Bean;

@org.springframework.context.annotation.Configuration
public MyConfic {

    @Inject MyEntity1Repo myEntity1Repo;
    @Inject MyEntity2Repo myEntity2Repo;

    @Bean(name="myEntity1Service")
    AbstractEntityService<MyEntity1, MyEntity1Repo> myEntity2Service(){
        return new AbstractEntityService<> myEntity1Service( myEntity2Repo );
    }

    @Bean(name="myEntity2Service")
    AbstractEntityService<MyEntity2, MyEntity2Repo> myEntity2Service(){
        return new AbstractEntityService<> myEntity2Service( myEntity2Repo );
    }

}

At least this way you don't have to create a separate subclass per entity. 至少通过这种方式,您不必为每个实体创建单独的子类。

Mind you, now you cannot do injection by type since after erasure your myEnity1Service you will have the same type as myEnity2Service : AbstractEntityService . 你要知道,现在你不能因为你的力擦除类型做注射myEnity1Service你将有相同的类型myEnity2ServiceAbstractEntityService Using something like 使用类似

@Inject @Named("myEntity2Service" )
AbstractEntityService<MyEntity2, MyEntity2Repo> myEntity2Service;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM