尝试@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
?
感谢您提供任何帮助!
答案 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>