问题
I have the following problem:
Suppose I have an abstract class lets say:
public abstract class AbstractHbmDao implements SomeInterface {
@Autowired
protected SessionFactory sessionFactory;
//getters & setters
//interface stuff
}
Then several implementations of SomeInterface
-> A_Interface
, B_Interface
, etc. This is ok if I use the same SessionFactory
for every implementation.
The problem is I want to use distinct SessionFactory
for distinct group of of implementations and I do not want to specify with the @Qualifier
. This would be less flexible to define these groups since I would need to change the code. Also by putting the SessionFactory
in the abstract class if would be impossible to specify with the @Qualifier
annotation.
Is there a way to do it in the xml bean definition ? I tried by declaring two SessionFactory
beans and for each of then ref the corresponding class, but this would still return NoUniqueBeanDefinitionException
.
回答1:
Field injection is fragile all on its own, and constructor injection should be preferred whenever possible. That's the clean solution here: Make an abstract (protected
) constructor on your base class that takes your bean as an argument, and use @Qualifier
on the subclass constructors.
回答2:
An alternative approach that uses Field injection is to not autowire the field in the base class, but instead creating an abstract method to get the SessionFactory and autowire the field in the subclasses.
public abstract class AbstractHbmDao implements SomeInterface {
protected abstract SessionFactory getSessionFactory();
}
And in subclasses implement this method:
public MyDao extends AbstractHbmDao {
@Autowired
@Qualifier("my-qualifier") // add qualifier as needed now
private SessionFactory sessionFactory;
protected SessionFactory getSessionFactory() { return sessionFactory; }
}
来源:https://stackoverflow.com/questions/26453618/autowire-distinct-beans-in-abstract-class