我今天遇到了这种混乱。引用Weld的文件(根据9.3节),
默认情况下,所有拦截器都被禁用。我们需要启用拦截器。我们可以使用bean归档的beans.xml描述符来完成它。但是,这种激活只适用于该归档文件中的bean。
但是,在我目前正在进行的项目中,我有一个用于分析方法的拦截器。我的META-INF/beans.xml基本上是空的:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>但是我仍然能从那个分析截取器得到预期的日志。因此,正如标题所示,拦截器在默认情况下真的是禁用的吗?
顺便说一句,我在项目中使用weld-se来实现CDI功能,因为CDI是我从Java堆栈中需要的项目唯一需要的东西。
更新
在今天讨论了拦截器之后,我发现如果使用旧的@Interceptors来指示拦截实现类,则不需要在beans.xml中指定任何内容。但是,如果使用拦截器绑定,即使用@Interceptor注释来指示拦截器类,则必须通过将拦截器类添加到beans.xml来启用拦截。根据我的经验,CDI1.1仍然如此,如上面beans.xml中的版本所示。顺便说一句,在这种情况下,我使用org.jboss.weld.se:weld-se:2.0.4.Final来实现CDI,我认为它实现了CDI1.1。
发布于 2013-12-01 02:25:30
在他的编辑中确认JBT的发现。按照CDI规范,JSR-299的1.0由焊接1.0实现,用于JEE6规范。请参考这个指针,我引用如下:
默认情况下,bean存档没有通过拦截器绑定绑定启用的拦截器。必须通过在
<class>的子<interceptors>元素中列出完全限定的类名来显式启用拦截器。,如下面的方法2所示
以下是一个例子:
第一个强制步骤是拦截器绑定:
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Loggable {
}第二个强制步骤是拦截类:
@Interceptor
@Loggable
public class LoggingInterceptor {
@AroundInvoke
public Object logMethodEntry(InvocationContext ctx) throws Exception{
System.out.println("In LoggingInterceptor..................... before method call");
Object returnMe = ctx.proceed();
System.out.println("In LoggingInterceptor..................... after method call");
return returnMe;
}
}第三步可以使用下列任何一种方法实现
方法1,一个空的beans.xml将完成这项工作
@Stateless
@Interceptors(LoggingInterceptor.class) //class interception
public class Displayer implements DisplayerLocal {
@Override
//@Interceptors(LoggingInterceptor.class) //method interception
public void displayHi() {
System.out.println(".....Hi there............");
}
}方法2,需要beans.xml,如下所示
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
<interceptors>
<class>com.companyname.LoggingInterceptor</class>
</interceptors>
</beans>然后被截获的类:
@Stateless
@Loggable //class interception
public class Displayer implements DisplayerLocal {
@Override
//@Loggable //method interception
public void displayHi() {
System.out.println(".....Hi there............");
}
}发布于 2013-10-15 07:11:26
拦截器和装饰器默认是从1.1版本启用的。请参阅新CDI规范的亮点。
https://stackoverflow.com/questions/19374263
复制相似问题