在这种情况下,我想编写一个过滤器,并希望该过滤器将一些对象插入当前请求中并将其传递,以便在资源类获得请求时可以使用该对象。
过滤等级
@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
@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
直接注入的另一种选择是使用HK2功能Jersey 2提供的功能。
创建一个工厂,注入ContainerRequestContext
并返回MyObject
。例如
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);
}
});
}
}
随着财产如上面的例子过滤器相同的设置,则可以只注射MyObject
用@Context
@GET
public Response getTest(@Context MyObject myObject) {
return Response.ok(myObject.getMessage()).build();
}
Custom Injection
也可以看看:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句