Java – provides Di methods in abstract classes
In most cases, I have many components with the same classes injected by OSGi declarative services These services will be used to execute logic that is the same for all derived components Therefore, in order to avoid duplication of code, it is best to use abstract classes Is it possible to move Di reference methods (set / unset) to abstract classes I'm using Bnd
For example:
@Component public class B implements IA { private ServiceC sc; @Reference public void setServiceC(ServiceC sc) { this.sc = sc; } public void execute() { String result = executeSomethingDependendOnServiceC(); // do something with result } protected String executeSomethingDependendOnServiceC() { // execute some logic } } @Component public class D implements IA { private ServiceC sc; @Reference public void setServiceC(ServiceC sc) { this.sc = sc; } public void execute() { String result = executeSomethingDependendOnServiceC(); // do something different with result } protected String executeSomethingDependendOnServiceC() { // execute some logic } }
I want to move serviceC's setter and executesomethingdependonservicec () methods to abstract classes But what does it have to do with Bnd annotations in OSGi? It doesn't work just to annotate this class with @ component, because a and D will create different instances of the abstract class, while @ component is an instance created by alsp
Maybe someone has the same problem and gives me some suggestions on how to solve it At least one best practice solution would also be good:)
Solution
DS annotation must be on the class instantiated for the component Comments on superclasses are not supported It has been suggested that changes be made in future versions of the specification
What you can do is move the method to the superclass, but you need to simply override the method in the subclass so that it can be annotated in the subclass