【问题标题】:Inject EJB into RESTeasy webservice将 EJB 注入 RESTeasy Web 服务
【发布时间】:2015-06-29 01:45:47
【问题描述】:

我目前在将@Stateless-EJB 注入到我的 RESTeasy 实现的 web 服务中时遇到问题:

资源:

import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/rest/events")
public class EventResource
{
@EJB
EventService eventService;

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllEvents()
{
    System.out.println(eventService);
    return Response.ok().build();
}

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Response getEventById(@PathParam("id") String id)
{
    System.out.println(id);
    int intId = Integer.parseInt(id);
    Event e = eventService.getById(intId);
    System.out.println(e);
    return Response.ok(e).build();
}

服务:

@Stateless
public class EventService
{
...
}

应用:

public class SalomeApplication extends Application
{
    private Set<Object> singletons = new HashSet();
    private Set<Class<?>> empty = new HashSet();

    public SalomeApplication()
    {
        this.singletons.add(new EventResource());
    }

    public Set<Class<?>> getClasses()
    {
        return this.empty;
    }

    public Set<Object> getSingletons()
    {
        return this.singletons;
    }
}

我正在使用org.jboss.resteasy:resteasy-jaxrs:3.0.11.FinalWildfly 和应用程序服务器。我也尝试使用 InjectRequestScoped 代替 - 也不起作用。

【问题讨论】:

    标签: java resteasy wildfly


    【解决方案1】:

    EventResource 的实例由您创建,由于您没有设置 EventService 引用,它当然必须是 null。 您还将此实例注册为 Singleton,因此您将始终准确地获得此实例。

    如果您将EventResource.class 添加到类集,RESTeasy 将负责创建实例并管理依赖项。如果您更喜欢使用单例,您应该使用自动扫描功能。在 Wildfly 上,这是默认启用的,因此您需要做的就是删除 SalomeApplication 的内容。

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-29
      • 2013-07-07
      • 2017-01-03
      • 2023-03-17
      相关资源
      最近更新 更多