简体   繁体   中英

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

@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.

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.

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 . Using something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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