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

标签 java osgi aem inject sling

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

服务实现:

@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), "");
    }
}

小服务程序:

@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 成功注入(inject)服务并可在 @SlingServlet doPost等方法:

@Reference
MyConfigurationService myConfigurationService;

为什么 @Inject@Reference 有效时无法将服务注入(inject)到 @SlingServlet 中?

感谢您提供的任何帮助!

最佳答案

我认为您将 sling 模型 @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 注释是通用的,被许多框架用于依赖注入(inject)。在 AEM 或 Sling 的情况下,它仅表示 Sling 模型(由 org.apache.sling.models.annotations.Model 注释的类)内部的某些内容,阅读有关 @Inject 和其他注释的更多信息用于此处的吊索模型:https://sling.apache.org/documentation/bundles/models.html#basic-usage

关于java - 吊索@Inject NullPointerError,当@Reference成功时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48816544/

相关文章:

java - Live Copy 上不会自动进行转出

java - SQLite语法错误但语句完全正确

java - 如何在 TextView 中显示一些文本指定的时间?

Java - 将类的引用传递给另一个类

java - PAX-CDI : how to get reference to BeanManager in bundle without using CDI

java - 如何解决 JPMS 和 OSGi Bundle for Eclipse plugin project an Tycho 之间的冲突

java - OSGI 有效版本范围

java - NetBeans 中的collectd 插件

docker - 麦克 |从 VirtualBox 机器上的另一个应用程序访问部署在 Docker 上的应用程序

html - Sightly:迭代一个列表并使用其索引打印另一个列表(不嵌套,只是共享索引)