简体   繁体   中英

How to inject dynamic Bean parameter into Jersey method?

I'm developing a webservice with Jersey 2.0 and Spring.

I want to be able to inject a bean into my methods. Bean parameters can be obtained using @BeanParam . However, I need a 'dynamic' bean injected. I need this bean to contain all of the query parameters passed to the method.

For example, if I make a request GET /posts?title=lorem&date=2011-01-01&tag=game

And I have a method like

@Path('/posts')
public class PostService{
    @GET
    public Response getAll(@QueryParam("page") int page,
        @QueryParam("pageSize") int pageSize,
        @BeanParam SearchParameters sp){

        sp.getTitle();
        sp.getDate();
        sp.getTag();
    }
}

I might be easier to get a map of query parameters Map<String, String> .

@BeanParam allows to put more injectable parameters into one bean (POJO), so that you do not have so many injectable parameters in the resource method, in resource method constructor or so many injectable fields in the resource class. You can encapsulate them into bean injected with @BeanParam. This deals with parameters like @HeaderParam, @QueryParam and such. But you can also inject ContainerRequestContext, UriInfo, SecurityContext or any other injectable object into your bean.

However, in your case you need to use the map of query parameters because you need all parameters and not only specific parameters known before. In order to get them, you can inject UriInfo and get query parameters from it:

@GET
public Response get(@Context UriInfo uriInfo) {
    MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
    String myParam = queryParameters.getFirst("myParam");    
    ...
}

Or you can use @BeanParam and inject @UriInfo into a bean.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM