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

Ale*_*sky 3 java osgi inject sling aem

当尝试@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), "");
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,使用@Reference(org.apache.felix.scr.annotations.Reference)代替@Inject成功注入服务,并且可以在以下@SlingServlet方法中使用doPost:

@Reference
MyConfigurationService myConfigurationService;
Run Code Online (Sandbox Code Playgroud)

为什么@Inject无法在服务@SlingServlet时注入服务@Reference

感谢您提供任何帮助!

Ahm*_*lam 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