简体   繁体   中英

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? ).

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.

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;
}

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