Failed to enter @ApplicationScoped bean in JAX-RS service

I created a JAX-RS service in which I want to enter a bean application scope. The problem is that the bean is not entered. How is this caused and how can I solve it?

JAX-RS Service:

@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 Applications

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;
    }

}
+5
source share
3 answers

You need to make the bean a managed resource so that it has the right to inject. At a minimal level, add @RequestScopedto the JAX-RS SIB to make it suitable for injection.

Another alternative annotation is @ManagedBean. The fact is that Jersey will not address the desired goal of the injection if the parent bean is not in a controlled 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();
    }
}

EDIT: beans.xml WEB-INF. beans.xml :

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

EDIT: JIRA @RequestScoped @ManagedBean

+5

, - EJB JSF.

, beans JAX-RS, , , , bean.

, CDI (beans.xml),

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

CDI Spring (no beans.xml), @Named

@Named
@Singleton
public class GameController {
    private Game game;
    public GameController() {
        this.game = new Game(new ArrayList<Room>());
    }
....
}

, JAX-RS @ManagedBean , , CDI JAX-RS.

+1

Add cdi-api.jar to your project.

-1
source

All Articles