Иван Гладуш
Иван Гладуш

Reputation: 642

How autowired bean based generic value in spring?

I have the following code structure

@Component
public class MyServiceUser{
    @Autowired
    private MyService<FirstMyDao> dao;

}

@Service
public class MyService<T extends AbstractMyDao>{

    @Autowired
    private T myDao;
}

abstract class AbstractMyDao{}
@Repository
class FirstMyDao extends AbstractMyDao{}

@Repository
class SecondMyDao extends AbstractMyDao{}

Spring said that he can't resolve which type of dao set in service. Can I do it? I read a few articles but didn't find the answer(https://blog.jayway.com/2013/11/03/spring-and-autowiring-of-generic-types/ , How to Autowire Bean of generic type <T> in Spring?).

Upvotes: 0

Views: 80

Answers (2)

Piotr Rogowski
Piotr Rogowski

Reputation: 3880

I think that you should use @Scope("prototype") in MyService

Bean with scope prototyp is create for each object where it is inject.

Example:

@Service
@Scope("prototype")
public class MyService<T extends AbstractMyDao>{

    @Autowired
    private T myDao;
}

Upvotes: 2

mikeb
mikeb

Reputation: 11267

I usually do something like this:

public class MyService<T extends AbstractMyDao>{

    private T myDao;
    public MyService(T dao){
        myDao = dao;
    }
}

@Configuration
public class ServiceConfig {
   @Bean 
   public MyService<FirstMyDao> myServiceFirstMyDao(FirstMyDao fmd){
        return new MyService(fmd);
   }
}

That should work because FirstMyDao fmd will get autowired and you will then have an injectable bean MyService<FirstMyDao>

Note that you remove the @Service from the generic class since Spring does not know what T is.

Upvotes: 2

Related Questions