当尝试使用 @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/