The problem is solved! I have just updated the version of maven-scr-plugin from 1.7.4 to 1.9.0 and it started to work! Now I am retrieving my instances via @Reference annotations and I see my service in "Services" and "Components" tabs in Felix OSGi Console. Thanks to all who replied here!
Adobe CQ: Injecting services via @Reference returns null
-
26-06-2023 - |
Question
I'm trying to inject a service into the component via @Reference annotation in Adobe CQ5, but after deployment it always returns null to me instead of service instance.
@Component(immediate = true)
@Service(value = GoodbyeWorldService.class)
public class GoodbyeWorldService {
@Reference
protected Scheduler scheduler;
private final static Logger LOGGER = LoggerFactory.getLogger(GoodbyeWorldService.class);
public void get() {
LOGGER.info("Scheduler is " + this.scheduler);
}
}
The JSP:
<%@ include file="/apps/cqblueprints-example/components/global.jspx" %>
<jsp:directive.page contentType="text/html" pageEncoding="UTF-8"/>
<jsp:useBean id="goodbye" class="com.cqblueprints.example.services.GoodbyeWorldService" scope="page" />
<% goodbye.get(); %>
In the log I get:
2014-04-02 12:24:09.999 INFO [com.cqblueprints.example.services.GoodbyeWorldService] Scheduler is null
I've tested other simple print methods from this bean. They are working like charm.
What am I missing?
Solution 2
OTHER TIPS
In order to have @Reference
fields injected by the OSGi, you can't treat your service as a Java bean. Use SlingScriptHelper
available as the sling
object in the JSP files to get the service in a proper way:
<% GoodbyeWorldService service = sling.getService(GoodbyeWorldService.class); %>
<%= service.get() %>
Full example:
<%@page session="false" import="your.package.GoodbyeWorldService"
%><%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0"
%><sling:defineObjects/><%
GoodbyeWorldService service = sling.getService(GoodbyeWorldService.class);
%><%= service.get() %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow