CDI不适用于简单的适配器

Pap*_*urf 5 cdi websphere-liberty ibm-mobilefirst mobilefirst-adapters open-liberty

我已将CDI功能添加到server.xml文件中<feature>cdi-1.2</feature>.

我的行家模块包含的beans.xml里面<module_name>/src/main/resources/META-INF的文件夹.

这是beans.xml内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">
</beans>
Run Code Online (Sandbox Code Playgroud)

但是当我使用@Inject注释它不起作用时,我的bean总是如此null.

码:

package ch.webapp.presentation;

...

@Path("/test/")
public class MyController {
    @Inject
    private MyService myService;

    @GET
    @Path("/foo/{count}")
    @OAuthSecurity(scope = "login")
    @Produces("application/json")
    public Response news(@PathParam("count") int count) {
        return Response
                .ok(myService.getBar(count))
                .build();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

那是我的豆子

package ch.webapp.service;

...

@RequestScoped
public class MyService {
    public String getBar(int count) {
        return "foo";
    }
}
Run Code Online (Sandbox Code Playgroud)

我通过扩展MFPJAXRSApplication类来初始化jax-rs

package ch.webapp;

...

public class AccountApplication extends MFPJAXRSApplication {
    @Override
    protected void init() throws Exception {
    }

    @Override
    protected void destroy() throws Exception {
    }

    @Override
    protected String getPackageToScan() {
        return getClass().getPackage().getName();
    }
}
Run Code Online (Sandbox Code Playgroud)

环境细节:

Launching mfp (WebSphere Application Server 8.5.5.8/wlp-1.0.11.cl50820151201-1942) on Java HotSpot(TM) 64-Bit Server VM, version 1.8.0_172-b11 (en_CH)

Console Product version: 8.0.0.00-20180717-175523
Run Code Online (Sandbox Code Playgroud)

怎么了?

mar*_*ess 1

首先,除非您对它们进行适当的注释,否则 websphere jax-rs 实现似乎不会自动集成 jax-rs 资源。

通过适当注释将 jax-rs 放入 CDI 托管上下文中

@Path("/test/")
@javax.enterprise.context.RequestScoped
public class MyController {

    @Inject
    private MyService myService;

    @GET
    @Path("/foo/{count}")
    @OAuthSecurity(scope = "login")
    @Produces("application/json")
    public Response news(@PathParam("count") int count) {
        return Response
                .ok(myService.getBar(count))
                .build();
    }

}
Run Code Online (Sandbox Code Playgroud)

还要确保用于您的服务的注释是 @javax.enterprise.context.RequestScoped