使用InterceptorBinding时拦截器无输出的问题求助
解决Interceptor Binding自定义注解拦截器不生效的问题
核心问题
在Jakarta EE 10(GlassFish 7)环境下,仅通过@InterceptorBinding和@Interceptor标注拦截器类不足以让容器激活它——这也是你之前用@Interceptors能生效的原因:该注解直接指定了要绑定的拦截器实例,而自定义绑定注解需要额外的激活配置。
修复步骤
1. 给拦截器类添加@Priority注解
在AuthInterceptor类上添加@Priority,明确告知容器要激活这个拦截器,并指定执行优先级(值越小优先级越高,推荐使用Interceptor.Priority.APPLICATION系列常量):
package com.aadhil.ejb.interceptor; import com.aadhil.ejb.annotation.Auth; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.Interceptor; import jakarta.interceptor.InvocationContext; import jakarta.interceptor.Priority; @Auth @Interceptor @Priority(Interceptor.Priority.APPLICATION + 100) // 添加此注解激活拦截器 public class AuthInterceptor { @AroundInvoke public Object authenticate(InvocationContext invocationContext) throws Exception { System.out.println("Auth Interceptor"); return invocationContext.proceed(); } }
2. (可选)改用标准日志API输出
System.out.println的输出可能在GlassFish中被定向到非主日志文件,改用Jakarta标准日志API确保日志出现在server.log中:
import java.util.logging.Logger; public class AuthInterceptor { private static final Logger logger = Logger.getLogger(AuthInterceptor.class.getName()); @AroundInvoke public Object authenticate(InvocationContext invocationContext) throws Exception { logger.info("Auth Interceptor"); // 替换System.out.println return invocationContext.proceed(); } }
原配置失效原因
@InterceptorBinding仅定义了注解与拦截器的绑定关系,但未告知容器需要激活该拦截器。@Interceptors是显式指定要应用的拦截器,容器会自动激活;而自定义绑定注解必须通过@Priority(无部署描述符场景)或beans.xml来启用拦截器。@Inherited在此场景无用,你的LoginImpl直接标注了@Auth,不存在注解继承的需求。
验证方式
- 重新部署应用到GlassFish 7。
- 调用
LoginImpl的login方法。 - 查看GlassFish安装目录下
domain/logs/server.log文件,应能看到"Auth Interceptor"的日志输出。
内容的提问来源于stack exchange,提问作者Aadhil Ahamed
相关产品推荐
相关产品推荐

