Spring. Dynamic dependency injection

烂漫一生 提交于 2019-12-23 00:52:42

问题


I have the following problem.

I have a generic class A

public class A<T, DAO extends JpaRepository<?, ?>>
{    

    @Autowired
    protected DAO daoObject;

    ......

and there I am trying inject a genreic DAO-object of the JpaRepository-type.

If I have only one implemetation of injected object(of JpaRepository), then there is no problem, but if I have more then one, then spring doesn't know which object it is to inject and throws an exception.

The question is: How can I dynamish based on generic information, inject the correct object?

Thank you.

public interface IRegisteredUserDAO extends JpaRepository<RegisteredUser, String> {

}


public interface IMailLogDao extends JpaRepository<MailLog, Long> {

   findByTo(String to);
}

and i used it so

public class RegisteredUserVM extends YBTableViewModel<RegisteredUser, IRegisteredUserDAO>
{

UPDATE:

public class MailLogVM extends YBTableViewModel<MailLog, IMailLogDao>
{    

}

回答1:


You should be able to do this using the latest Spring 4 RC1. Versions before that do not support generic injection at all. See this ticket and related commits for details.




回答2:


You can use Spring's @Qualifier annotation to inject the correct bean:

@Autowired
@Qualifier("IRegisteredUserDAOImpl")
protected DAO daoObject;

Here the bean with qualifier value "IRegisteredUserDAOImpl" is wired.



来源:https://stackoverflow.com/questions/19808914/spring-dynamic-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!