吊索@Inject NullPointerError,当@Reference成功时

时间:2018-02-15 21:25:02

标签: java osgi aem inject sling

尝试@Inject(javax.inject.Inject)在MyConfigurationService内注入@SlingServlet MyServlet会导致NullPointerError随时在myConfigurationService上尝试任何操作在使用Maven org.apache.felix.maven-scr-plugin作为构建过程的一部分的AEM OSGi容器中。

服务实施:

@Service({MyConfigurationService.class})
@Component(immediate = true, metatype = true, label = "My Configuration Service")
public class MyConfigurationServiceImpl implements MyConfigurationService {
    @Property(unbounded = PropertyUnbounded.DEFAULT, label = "API URL", description = "API URL")
    private static final String API_URL = "apiurl";

    private String apiUrl;

    @Activate
    protected void activate(Map<String, Object> properties) {
        this.apiUrl = PropertiesUtil.toString(properties.get(API_URL), "");
    }
}

的Servlet

@SlingServlet(paths = "/bin/myServlet", methods = "POST", metatype = true)
public class MyServlet extends org.apache.sling.api.servlets.SlingAllMethodsServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger logger = LoggerFactory.getLogger(MyServlet.class);

    @Inject
    MyConfigurationService myConfigurationService;

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {
        // any attempts to use myConfigurationService results in NPE
    }
}

然而,使用@Reference(org.apache.felix.scr.annotations.Reference)代替@Inject成功注入了服务,并且可以在@SlingServlet方法中使用,例如{{ 1}}:

doPost

@Reference MyConfigurationService myConfigurationService; 工作时,为什么@Inject无法将服务注入@SlingServlet

感谢您提供任何帮助!

1 个答案:

答案 0 :(得分:5)

我认为你将吊索模型@Inject与maven SCR插件使用的SCR注释混淆。

maven SCR插件定义了要在build time处理的注释,这些注释在此处定义:http://felix.apache.org/documentation/subprojects/apache-felix-maven-scr-plugin/scr-annotations.html 所有这些注释都在包org.apache.felix.scr.annotations

@Reference注释只能与@ Component,@ service,@SlingServlte或任何其他定义OSGI组件的SCR类注释一起使用。

javax.inject.Inject注释是通用的,并且被许多框架用于依赖注入。在AEM或Sling的情况下,它仅表示Sling模型(由org.apache.sling.models.annotations.Model注释的类)中的内容,更多地了解@Inject以及可在此处使用Sling模型的其他注释:https://sling.apache.org/documentation/bundles/models.html#basic-usage < / p>