如何将对象注入球衣请求上下文?

我有这样一个场景,我想编写一个过滤器,我希望这个过滤器将一些对象插入到当前请求中并传递它,以便当资源类收到请求时它可以使用该对象.

I have this scenario where I want to write a filter and I want this filter to insert some object into the current request and pass it on so that when the resource class gets the request it can use the object.

过滤器类

@Override
public void filter(ContainerRequestContext request) throws IOException {
    MyObject obj = new MyObject();
    // Inject MyObject to request which I dont know how
}

资源类

@PUT @Consumes("application/json")
@Path("/")
public String create(
        JSONParam sample,
        @Context MyObject obj) {

    System.out.println(obj.getName());

    return "";
}

推荐答案

你可以只使用 ContainterRequestContext.setProperty(String, Object).然后只需注入 ContainerRequestContext

You could just use ContainterRequestContext.setProperty(String, Object). Then just inject the ContainerRequestContext

@Override
public void filter(ContainerRequestContext crc) throws IOException {
    MyObject obj = new MyObject();
    crc.setProperty("myObject", myObject);
}

@POST
public Response getResponse(@Context ContainerRequestContext crc) {
    return Response.ok(crc.getProperty("myObject")).build();
}

另一个直接注入 MyObject 的选项是使用 Jersey 2 提供的 HK2 功能.

Another option to inject the MyObject directly is to use the HK2 functionality Jersey 2 offers.

创建一个工厂,注入 ContainerRequestContext 并返回 MyObject.例如

Create a factory the inject the ContainerRequestContext and return the MyObject. For example

import javax.inject.Inject;
import javax.ws.rs.container.ContainerRequestContext;
import jetty.plugin.test.domain.MyObject;
import org.glassfish.hk2.api.Factory;

public class MyObjectFactory implements Factory<MyObject> {
    
    private final ContainerRequestContext context;
    
    @Inject
    public MyObjectFactory(ContainerRequestContext context) {
        this.context = context;
    }

    @Override
    public MyObject provide() {
        return (MyObject)context.getProperty("myObject");
    }

    @Override
    public void dispose(MyObject t) {}  
}

然后你需要绑定工厂:

public class InjectApplication extends ResourceConfig {
    
    public InjectApplication() {
        ...
        register(new AbstractBinder(){
            @Override
            protected void configure() {
                bindFactory(MyObjectFactory.class)
                        .to(MyObject.class)
                        .in(RequestScoped.class);
            } 
        });
    }
}

使用与上面过滤器示例中相同的属性设置,您可以只用 @Context

With the same setting of the property as in the filter example above, you can then just inject the MyObject with the @Context

@GET
public Response getTest(@Context MyObject myObject) {
    return Response.ok(myObject.getMessage()).build();
}


  • 自定义注入中查看更多信息李>


    • See more at Custom Injection
    • 有关此实现的问题,请参阅此问题.

      Please see this question for a problem with this implementation.

      另请参阅:

      • 如果您使用的是 web.xml 而不是 ResourceConfig

相关文章