I have an object that is created during the course of a request, and I'd like that object to call a service. However, when the framework calls the bind methods, it binds to its own instance of the class, not the one I want to bind to.
public class A {
final X x;
final Y y;
public A(Z z) {
this.x = z.x;
this.y = z.y;
}
public String doStuff() {
//do stuff
//call a service
}
}
public class B extends RestAPIServlet {
public String method(@SlingRequest SlingHttpServletRequest request, @SlingResponse SlingHttpServletResponse response) {
Z z = new ObjectMapper().readValue(request.getReader(), Z.class);
return new A(z).doStuff();
}
}
public class C extends TagSupport {
public int doStartTag() {
Z z = getZFromProperties();
String res = new A(z).doStuff();
pageContext.setAttribute("res", res);
return super.doStartTag();
}
}
Is there some way to call a service directly from A? Is there a preferred pattern for code reuse in the situation where you have a tag and a servlet performing the same work?
I've been asked not to make the tag/servlet implement a common interface to give A the service, nor to use a Supplier to give it access to the service through the tag/servlet.
BundleContext can be retrieved using the FrameworkUtil helper class and that, in turn, can be used to get to the service that you want to use. Here is an example:
BundleContext bundleContext = FrameworkUtil.getBundle(A.class).getBundleContext();
ServiceReference serviceRef = bundleContext.getServiceReference(MyService.class.getName());
MyService myService = (MyService) bundleContext.getService(serviceRef);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With