I solved a similar problem like you. I found another way, you do not need to create customization methods. Use regular constructors instead, but use autwiring Spring. Here is the complete code:
Service classes:
public abstract class AbstractService { protected final AbstractDAO dao; // Constructor forces you to inject dao in subclass public AbstractService(final AbstractDAO dao) { this.dao = dao; } public final void service() { // you can do something generic here with 'dao' // no matter which subclass is injected this.dao.doSomething(); } } @Component public class ServiceClassA extends AbstractService { @Autowired public ServiceClassA(@Qualifier("daoClassA") final AbstractDAO dao) { super(dao); } } @Component public class ServiceClassB extends AbstractService { @Autowired public ServiceClassB(@Qualifier("daoClassB") final AbstractDAO dao) { super(dao); } }
Pay attention to @Qualifier("daoClassA")
in subclass constructors
Field Classes:
public interface AbstractDAO { public void doSomething(); } @Component public class DaoClassA implements AbstractDAO { @Override public void doSomething() { System.out.println("I am DaoClassA"); } } @Component public class DaoClassB implements AbstractDAO { @Override public void doSomething() { System.out.println("I am DaoClassB"); } }
And finally, now you can call your shared service a specific service class and a specific DAO class: (of course, you can have them auto-field them somewhere)
((AbstractService) context.getBean("serviceClassA")).service(); ((AbstractService) context.getBean("serviceClassB")).service();
will print:
I am DaoClassA I am DaoClassB
source share