【发布时间】:2019-01-23 13:23:37
【问题描述】:
我已将 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
怎么了?
【问题讨论】:
-
是
MyService定义为 CDI bean 还是有明确的生产者 (@Produces) 方法? -
(要将
MyService定义为CDI bean,您只需将@ApplicationScoped或@RequestScoped放在MyService类上) -
MyService类被注释为@Stateless -
您确定为 JAX-RS 资源激活了 CDI 吗?它可能需要一些额外的配置(我不知道,因为我不知道 Websphere)。是
MyService@Stateless,还是@RequestScoped?两者兼有没有多大意义!它与MyController位于同一个jar 中吗?如果没有,jar 中是否有包含MyService的 beans.xml?还要确保@RequestScoped是javax.enterprize.context而不是javax.faces.bean下的那个! -
您是否以通常的方式直接通过 http 客户端访问资源?我想确定您不是自己构建 MyController。
标签: ibm-mobilefirst cdi websphere-liberty mobilefirst-adapters open-liberty