从头开始没有任何以前的Jersey 1.x知识,我很难理解如何在我的Jersey 2.0项目中设置依赖注入.
我也明白HK2可用于Jersey 2.0,但我似乎无法找到有助于Jersey 2.0集成的文档.
@ManagedBean
@Path("myresource")
public class MyResource {
@Inject
MyService myService;
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/getit")
public String getIt() {
return "Got it {" + myService + "}";
}
}
@Resource
@ManagedBean
public class MyService {
void serviceCall() {
System.out.print("Service calls");
}
}
Run Code Online (Sandbox Code Playgroud)
的pom.xml …
我已经能够根据如何将对象注入到球衣请求上下文中从过滤器注入我的球衣资源?.这允许我成功注入方法参数:
@GET
public Response getTest(@Context MyObject myObject) { // this works
Run Code Online (Sandbox Code Playgroud)
但是,对于setter/field/constructor注入,HK2 Factory 在jersey过滤器之前调用,这意味着provide()方法返回null:
@Override
public MyObject provide() {
// returns null because the filter has not yet run,
// and the property has not yet been set
return (MyObject)context.getProperty("myObject");
}
Run Code Online (Sandbox Code Playgroud)
有没有办法定义何时运行HK2 Factory以便在过滤器运行后调用它?如果没有,则解决方法是将MyObject定义为接口,并定义在其构造函数中采用ContainerRequestContext的其他实现; 任何实际使用该实例的尝试都将懒惰地委托给在ContainerRequestContext属性上设置的实现(可能在过滤器运行之前你不会实际使用该实例 - 此时将设置该属性).
但我想了解是否有可能延迟HK2工厂运行的点,使其在过滤器之后运行(在方法参数注入的情况下,它已在过滤器之后运行).如果不可能,那么我想了解是否存在根本原因.
我正在使用Jersey 1.12并且有一个端点,可能会或可能不会从我无法控制的客户端接收格式错误的标头(例如"Content-Type":"application/json; bla-bla")显然bla-bla格式不正确,因为规范要求参数也有值bla-bla=value,因此Jersey会输出一些东西喜欢
"status": 400,
"message": "Bad Content-Type header value: 'application/json; bla-bla'"
Run Code Online (Sandbox Code Playgroud)
我可以写一个过滤器来处理这里,这里和这里的建议,但是我想知道是否有一种方法可以让Jersey 在我对它的价值不感兴趣的情况下一起忽略格式错误的标题?
我已经实现了一个ContainerRequestFilter执行基于JWT的身份验证:
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
AuthenticationResult authResult = ...
if (authResult.isSuccessful()) {
// Client successfully authenticated.
// Now update the security context to be the augmented security context that contains information read from the JWT.
requestContext.setSecurityContext(new JwtSecurityContect(...));
} else {
// Client provided no or an invalid authentication token.
// Deny request by sending a 401 response.
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我更新了SecurityContext请求,JwtSecurityContext如果身份验证成功,则将其设置为我自己的自定义实现()的实例.此实现添加了额外的身份验证和授权数据,我希望稍后在后续过滤器和我的资源方法中访问这些数据. …