Java Spring + Jersey subresource: inject constructor-arg at runtime

喜欢而已 提交于 2020-08-19 11:00:58

问题


I have the following method defined, returning a bean that represents a subresource locator (Jersey):

@Path("{slug}")
public PageResource page( 
        @PathParam("slug") String siteSlug) throws AppException { 

    siteService.getSiteBySlug(siteSlug); //Validate if exists, else throw error 

    return (PageResource) appContext.getBean("pageResource", siteSlug); 
}

pageResource has prototype scope defined in applicationContext.xml.

Question: what is the alternative way for injecting the bean into the current class, while passing the constructor-arg at runtime?
I'm not comfortable getting the bean explicitly from the application context.

Edit for @peeskillet:

The subresource:

public class PageResource {
    @Autowired
    IPageService pageService; 

    String siteSlug; 

    public void setPageService(IPageService pageService){
        this.pageService = pageService; 
    }

    public PageResource(){}

    public PageResource(String siteSlug){ //***Inject siteSlug from parent here***
        this.siteSlug = siteSlug; 
    }; 

    @POST
    @Path("/pages")
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_JSON })
    public Response createPage(@NotNull @Valid Page page) throws AppException{ 
        System.out.println(pageService);
        ObjectId pageId = pageService.createPage(page); 
        page.setId(pageId); 

        return Response
                .status(Response.Status.CREATED)// 201 
                .entity(page)
                .header("Location", 
                        "http://localhost:8000/zwoop-v001/sites/" + this.siteSlug + 
                        "/pages/" + page.getSlug()).build(); 
    }
} 

回答1:


What you can do is inject ResourceContext, and resolve the sub-resource instance through that.

The resource context can be utilized when instances of managed resource classes are to be returned by sub-resource locator methods. Such instances will be injected and managed within the declared scope just like instances of root resource classes.

As stated, you can obtain instances of your sub-resources classes, and all the injections will be handled

@Path("root")
public class Resource {

    @Context
    ResourceContext context;

    @Path("sub/{id}")
    public SubResource get() {
        return context.getResource(SubResource.class);
    }
}

@PathParams are also resolved as injections into your sub-resource instance. So you could just do

class SubResource {

    @Autowired
    Service service;

    @PathParam("id")
    long id;
}

And when the sub-resource instance gets resolved, it will be injected with the service and the path param.



来源:https://stackoverflow.com/questions/38428397/java-spring-jersey-subresource-inject-constructor-arg-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!