无法在JAX-RS服务中注入@ApplicationScoped bean [英] Unable to inject @ApplicationScoped bean in JAX-RS service

查看:172
本文介绍了无法在JAX-RS服务中注入@ApplicationScoped bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了JAX-RS服务,我想在其中注入应用程序范围的bean.问题是没有注入bean.这是怎么引起的,我该如何解决?

I've created JAX-RS service in which I want to inject an application scoped bean. The problem is that the bean is not injected. How is this caused and how can I solve it?

JAX-RS服务:

@Path("room")
public class RoomService {

    @Inject
    GameController gc;

    public RoomService() {}

    @Path("create")
    @GET
    @Produces("application/json")
    public String create() {
        Room r = new Room();
        gc.addRoom(r); // gc is null
        return r.toJson();
    }
}

应用程序作用域bean

Application scoped bean

import java.util.ArrayList;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import pepuch.multuplayergameserver.entity.Game;
import pepuch.multuplayergameserver.entity.Room;

@Named
@ApplicationScoped
public class GameController {

    private Game game;

    public GameController() {
        this.game = new Game(new ArrayList<Room>());
    }

    public boolean addRoom(Room room) {
        if (!game.getRooms().contains(room)) {
            return game.getRooms().add(room);
        }

        return false;
    }

}

推荐答案

您需要使bean成为托管资源,使其有资格进行注入.至少要将@RequestScoped添加到JAX-RS SIB,使其值得注入.

You need to make the bean a managed resource to make it eligible for injection. At the bare minimum, add @RequestScoped to the JAX-RS SIB to make it injection-worthy.

另一个替代注释是@ManagedBean.关键是,如果父bean不在托管上下文中,则Jersey将无法满足所需的注入目标

Another alternative annotation is @ManagedBean. The point is , Jersey won't address the desired injection target, if the parent bean is not in a managed context

import javax.enterprise.context.RequestScoped

@RequestScoped
@Path("room")
public class RoomService {

    @Inject
    GameController gc;

    public RoomService() {}

    @Path("create")
    @GET
    @Produces("application/json")
    public String create() {
        Room r = new Room();
        gc.addRoom(r); // gc is null
        return r.toJson();
    }
}

确保您的WEB-INF文件夹中有一个 beans.xml 文件.您的beans.xml文件将类似于:

be sure to have a beans.xml file in your WEB-INF folder. Your beans.xml file will look something like:

  <beans xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">   

  </beans>

基于此JIRA ,您可以将@RequestScoped替换为

Based on this JIRA, you may replace @RequestScoped with @ManagedBean

这篇关于无法在JAX-RS服务中注入@ApplicationScoped bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆