gpt4 book ai didi

jersey - 使用 ejb 注入(inject)测试 rest 端点服务

转载 作者:行者123 更新时间:2023-12-02 03:22:13 25 4
gpt4 key购买 nike

我有一个 jax-rs 资源

@Path("rest/v1/serviceemail")
public class PreviewResource implements Preview
{
@EJB
private Mapper mapper;

我正在使用 jersey-test-framework-core 和 jersey-test-framework-grizzly2 创建一个 IT 测试。

当我启动测试时,ejb 没有注入(inject)到服务中,所以我收到了 NPE。

最佳答案

我通过实现自定义 InjectableProvider 找到了解决方案。以下代码取自 Oracle article :

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.ext.Provider;

import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;

@Provider
public class EJBProvider implements InjectableProvider<EJB, Type> {

public Scope getScope() {
return Scope.Singleton;
}

public Injectable getInjectable(ComponentContext cc, EJB ejb, Type t) {
if (!(t instanceof Class)) return null;

try {
Class c = (Class)t;
Context ic = new InitialContext();

final Object o = ic.lookup(c.getName());

return new Injectable<Object>() {
public Object getValue(HttpContext c) {
return o;
}
};
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

我不得不稍微调整它以适应我的环境。另请注意,提供者必须与您的服务类在同一个包中,否则将不会被拾取(在文章中没有说明)。

关于jersey - 使用 ejb 注入(inject)测试 rest 端点服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32581151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com