Reputation: 809
I have a listener class hierarchy consisting of a base class into which I autowire a base service MyBaseService
.
I extend MyBaseService
to more concrete sub service classes so in order to make specific implementations for sub listeners.
Using Spring, how do I specify that a specific sub listener class needs to use a specific sub service class?
Here's a diagram:
Code examples:
Services
public interface BaseService<TContext extends ProcessContext, TTabel extends Tabel> { .. }
public interface SubService extends BaseService <B, BT> { .. }
---- (Implementations of these interfaces in service classes)
Listener classes:
public abstract class AbstractListener {
@Autowired
private BaseService baseService;
public someFunction() {
baseService.DoStuff(); //SubServiceImpl Also have a dostuff implementation
}
}
public SubListenerA extends AbstractListener {
//I need to specify that we will now use subService so subservices DoStuff() is used insted of base services doStuff()
}
I don't want to override someFunction.
Upvotes: 1
Views: 963
Reputation: 10653
You have to create beans of Listener
classes also, as they're going to be used finally to call service classes. Since we can't have same reference pointing to different beans, we need different beans for it.
Please take a look at the sample below,
package com.test;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class TestChildInjectionApplication {
@Autowired
private SubListenerA listenerA;
@Autowired
private SubListenerB listenerB;
@PostConstruct
public void init () {
listenerA.doSomething();
listenerB.doSomething();
}
public static void main(String[] args) {
SpringApplication.run(TestChildInjectionApplication.class, args);
}
}
class BaseListener {
private BaseService service;
public BaseListener(BaseService service) {
super();
this.service = service;
}
public void doSomething() {
service.doStuff();
}
}
@Component
class SubListenerA extends BaseListener {
public SubListenerA(ServiceA service) {
super(service);
}
}
@Component
class SubListenerB extends BaseListener {
public SubListenerB(ServiceB service) {
super(service);
}
}
class BaseService {
public void doStuff() {
System.out.println("################################## in: " + this.getClass());
}
}
@Component
class ServiceA extends BaseService {}
@Component
class ServiceB extends BaseService {}
Upvotes: 1