如何使用apache cxf创建具有Spring依赖关系的子资源@autowired

时间:2014-06-18 03:23:42

标签: spring cxf jax-rs

我无法弄清楚如何在子资源中使用spring来自动连接依赖项。我需要为子资源指定一些请求状态。我还需要访问cxf托管的@Contexts。

如果我有课

@Path("/resource/")
public class Resource {
    @Autowired
    private dependency

    @Path("{id}/sub/")
    public getSub(@PathParam("id") String id){
      // I know this is not right. I could autowire subresource, but it needs
      // to be request scoped and I get errors about proxying request scoped bean
      // into singleton bean. 

      // I have also tried instantiating the subresource using ResourceContext 
      // but then Subresource's dependencies don't get injected
      return new Subresource(id);
    }
}

另一个班级

public class Subresource{

    @Context
    private UriInfo uriInfo;

    @Autowired
    private Dependency2 dependency2;

    private String id;
    public Subresource(String id){

    }
    @GET
    public Response get(){
       return Response.ok(id).build();
    }
}

如何将弹簧管理的依赖项自动注入子资源?子资源如何访问CXF托管依赖项?

1 个答案:

答案 0 :(得分:0)

我创建工厂bean来实例化子资源:

public class SubResourceFactory {
    @Autowired
    private AutowireCapableBeanFactory autowireBeanFactory;

    public SubResource createBean(String parameter1, Parameter2 parameter2) {
        ... creating SubResource instance, setting parameters to it

        autowireBeanFactory.autowireBean(subResource);
        return (SubResource) autowireBeanFactory.initializeBean(subResource, "subResource");
    }
}

AutowireCapableBeanFactory允许在Spring Context之外创建init bean并向其注入任何Spring bean。 SubResourceFactory在我的项目中被实例化为Spring单例bean并注入Root Resource,所以我可以像这样使用它:

@Resource
private SubResourceFactory subResourceFactory;

@Override
public SubResource getInfoFromSubResource(String parameter1) {
    Parameter2 parameter2 = parameter2StoreService.getParameter2(parameter1);
    return subResourceFactory.createBean(parameter1, parameter2);
}

但是这个subResource只由Spring管理,所以你只能注入Spring bean,你不能注入CXF-RS @Context bean。 必须有一种方法可以做同样的事情来允许使用ResourceContext进行Spring和CXF-RS注入,但我现在可以看到,它只注入了CXF-RS bean,根本没有注入Spring。