我已经编写了以下用于在EJB中测试InterceptorBinding的测试代码,如here所述:
Bean类:
@Stateless
@LocalBean
@Interceptors ({LoggingInterceptor.class})
public class TestInterceptor {
@PostConstruct
public int func1()
{
System.out.println("here1");
return 0;
}
public void func2()
{
System.out.println("here2");
}
public static void main(String[] args)
{
TestInterceptor t = new TestInterceptor();
t.func1();
t.func2();
}
}
拦截器绑定:
@InterceptorBinding
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}
拦截器: @Interceptor @Log 公共类LoggingInterceptor {
private java.util.logging.Logger logger =
java.util.logging.Logger.getLogger("theLogger");
@AroundInvoke
public Object intercept(InvocationContext context) throws Exception {
logger.log(Level.INFO, "here ", context.getMethod().getName());
return context.proceed();
}
}
JSP文件:
<%@page import="test.TestInterceptor"%>
<%@page import="javax.ejb.EJB"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%
TestInterceptor object = new TestInterceptor();
%>
<%=object.func1()%>
</body>
</html>
但是没有调用拦截方法。你能帮我解决一下这个问题吗?
答案 0 :(得分:4)
您正在直接实例化TestInterceptor,这意味着EJB容器没有机会应用拦截器。即使对于@LocalBean,这也行不通。您需要查找或注入对EJB的引用。