Search code examples
javaspringspring-annotationsspring-bean

autowire distinct beans in abstract class


I have an abstract class:

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.


Solution

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