这是我在这里的第一篇文章,祝大家有美好的一天:)
我创建了一个名为“Validate”的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Validate {
Class<? extends MethodInterceptor>[] value();
}
然后在需要拦截的方法前进行装饰
@Validate({OneInterceptor.class, TwoInterceptor.class})
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
//Do something
}
OneInterceptor implements MethodInterceptor {.....} TwoInterceptor implements MethodInterceptor{....}
是否可以使用 Guice 来绑定(bind)这样的拦截器?我只想让 Guice 在运行时动态地绑定(bind)这些拦截器。 谢谢大家!
最佳答案
正如 mlk 所指出的,您可以编写一个 MethodInterceptor 来执行此操作,尽管没有理由提到的 validator 也必须是 MethodInterceptors——而且,事实上,这样做可能会更容易,因为您没有担心 proceed()
。
如果此代码无法编译,请原谅我,但它应该为您指明了正确的方向:
public interface RequestValidator {
void validate(HttpServletRequest req) throws ValidationError;
}
public class ValidationModule extends AbstractModule {
@Override public void configure() {
bindInterceptor(Matchers.any(), Matchers.annotatedWith(Validate.class),
new ValidateInterceptor());
}
}
public class ValidateInterceptor implements MethodInterceptor {
@Override public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
Validate validate = method.getAnnotation(Validate.class);
if (validate == null) {
throw new IllegalStateException(
"ValidateInterceptor installed on non-@Validate method");
}
for (Class<? extends RequestValidator> validatorClass : validate.value()) {
RequestValidator validator = validatorClass.newInstance();
validator.validate((HttpServletRequest) invocation.getArguments()[0]);
}
return invocation.proceed();
}
}
关于java - 有没有可能通过使用 Guice 来拦截这样的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14232695/