CDI在简单的适配器中不起作用

时间:2018-08-16 14:28:52

标签: ibm-mobilefirst cdi websphere-liberty mobilefirst-adapters open-liberty

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

我的maven模块在<module_name>/src/main/resources/META-INF文件夹中包含 beans.xml

这是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>

但是当我使用@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();
    }
}

编辑:

那是我的豆子

package ch.webapp.service;

...

@RequestScoped
public class MyService {
    public String getBar(int count) {
        return "foo";
    }
}

我通过扩展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();
    }
}

环境详细信息:

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

怎么了?

3 个答案:

答案 0 :(得分:1)

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

通过适当地注释jax-rs到CDI管理的上下文中

my_list = []
my_list.append(list_element)

还请确保用于您的服务的注释是 @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(); } }

答案 1 :(得分:0)

根据您提供的输入,请仔细阅读以下清单。

  1. 您的服务和控制器位于同一模块中,并且其包装类型为war,因此必须将beans.xml放在此路径src/main/resources/WEB-INF/beans.xml中。 (如果这是Java EE 7应用程序,那么beans.xml是可选的。
  2. 在您的AccountApplication类中,尝试将包名称硬编码为ch.webapp.presentation

    @Override     受保护的字符串getPackageToScan(){         返回“ ch.webapp.presentation”;     }

这仅是为了检查MFPJAXRSApplication.getPackageToScan()方法的行为,是仅扫描指定的程序包还是其子程序包。

  1. 除了这些,对我来说一切似乎还不错。如果仍然不能解决问题,请添加完整的应用程序启动日志,以便社区可以找到它的根本原因。

答案 2 :(得分:-2)

这是经典错误。 CDI适用于托管 Bean(例如EJB和Servlet)。如果要在JAXRS Bean上启用它,则必须将其设置为“托管”,即将MyController注释为(例如javax.annotation.ManagedBeanjavax.ejb.Stateless

还要注意,对于webapp(.war),beans.xml文件必须位于WEB-INF文件夹中!