Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to use Restful and CDI working together?

I tried to build a project using CDI and Restful working together (Publish a Restful service from a CDI bean) but I couldn't find a way to do that.

Somebody know how they can work together without EJBs?.

like image 884
maframaran Avatar asked Dec 13 '25 18:12

maframaran


1 Answers

With talking about Restful, I assume you mean Jax-RS. Take a the following code:

UserResource.java

This class implements the RESTful API accessing a use case GetUser and returning its result.

@Path("users")
@ApplicationScoped
public class UserResource {

    @Inject
    private GetUser getUser;

    @GET
    public Response getUser(@QueryParam("userId") String userId) {
        return UserRepresentationMapper.toRepresentation(getUser.getUser(userId);
    }
}

GetUser.java

The GetUser use case uses some dependencies (here a UserService) to get its data and do something with it.

@ApplicationScoped
public class GetUser {

    @Inject
    private UserService userService;

    public ApplicationUser getUser(String userId) {
        // ...
    }
}

and have a beans.xml within your META-INF (jar) or WEB-INF (war) directory to activate CDI (JEE6, beans.xml is not needed when using JEE7 and all your classes are annotated with bean defining annotations).

like image 170
mp911de Avatar answered Dec 16 '25 08:12

mp911de



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!