Expand my Community achievements bar.

@Reference Annotation not working in aem Fiddle Script for JSP and servlets

Avatar

Level 1

It complains 

Compilation errors in /apps/acs-tools/components/aemfiddle/fiddle/fiddle.java: Line 15, column 396 : Only a type can be imported. org.osgi.service.component.annotations.Reference resolves to a package

 

Found out one solution and gets the work done:

getService(MyService.class);

 

static <T> T getService(Class<T> serviceClass) {
BundleContext bContext = FrameworkUtil.getBundle(serviceClass).getBundleContext();
ServiceReference sr = bContext.getServiceReference(serviceClass.getName());
return serviceClass.cast(bContext.getService(sr));
}

 

Any better way to do it?

Topics

Topics help categorize Community content and increase your ability to discover relevant content.

4 Replies

Avatar

Community Advisor

Hi, 


You can use it from slingBinding instead:

 

public class fiddle extends SlingAllMethodsServlet {
    //Any OSGI service you will normally use through 
    MyService service = null; 
    SlingScriptHelper scriptHelper = null;
    
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {

        SlingBindings bindings = (SlingBindings) request.getAttribute(SlingBindings.class.getName());
        scriptHelper = bindings.getSling();
        //Here you get the OSGI service
        service = scriptHelper.getService(MyService.class);

 


Hope this helps.



Esteban Bustamante

Thanks @EstebanBustamante  That works as well. Seems it depends on the usecase and need. Both solutions with BundleContext and SlingBindings would work.

Avatar

Level 10

@antarikshruhil9 There is some issue I am seeing with the fiddle as it is not compiling imports. Removing some keywords from import package also not giving any exception/error. That's because it is not able to resolve any Java file.

Avatar

Administrator

@antarikshruhil9 Did you find the suggestions from users helpful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.



Kautuk Sahni