官术网_书友最值得收藏!

Interceptor types

One of the interesting features in CDI is that we can introduce interceptors using qualifiers. Let's define one interceptor called LoggedInterceptor, which is supposed to perform logging functionalities on a big set of CDI beans in some enterprise application:

@Interceptor 
@Logged 
public class LoggedInterceptor { 
 
    @AroundInvoke 
    public Object interceptMethod(InvocationContext ctx) throws Exception { 
        Object retValue = ctx.proceed(); 
        return "intercepted " + retValue; 
    } 
} 

Note that in this example, we have annotated the interceptor with the @Logged annotation. This is a qualifier annotation that we will define as shown earlier, in the Using qualifiers section, as follows:

@InterceptorBinding 
@Target({TYPE, METHOD}) 
@Retention(RUNTIME) 
public @interface Logged { 
} 

By annotating LoggedInterceptor with the qualifier @Logged, we can later annotate any CDI bean with the @Logged qualifier, to tell the container that we wish to use the LoggedInterceptor with that CDI bean, as follows:

@Dependent 
@Logged 
public class MyPojo { ... } 

This is equivalent to the previous example, where we annotated MyPojo with the @Interceptors annotation. However, by using the qualifier rather than the interceptor class itself, we have abstracted MyPojo from the real interceptor implementation, and thus we can later alter this class type, or replace it among deployment modes (production or testing).

All CDI interceptors defined in this way are disabled by default. To make them enabled, you should define a WEB-INF/beans.xml file as the final step, with the following XML code:

<?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" 
       bean-discovery-mode="annotated"> 
    <interceptors> 
        <class>com.example6.LoggedInterceptor</class> 
    </interceptors> 
</beans> 
Note that without defining the interceptor in  beans.xml, our example will not work as expected.

We can also apply qualified interceptors on singular methods as follows:

@Dependent 
public class MyPojo { 
 
    @Logged 
    public String getMessage1() { 
        return "MyPojo first message!"; 
    } 
    ... 
} 
主站蜘蛛池模板: 遂川县| 邵阳县| 冕宁县| 莱芜市| 海丰县| 东阳市| 水城县| 芦山县| 二连浩特市| 建水县| 渝北区| 商洛市| 木里| 郧西县| 嘉祥县| 莱西市| 名山县| 武安市| 酉阳| 新闻| 永年县| 濉溪县| 贡嘎县| 乾安县| 桐柏县| 南充市| 余江县| 吉首市| 永登县| 澎湖县| 方正县| 淮阳县| 望城县| 霍林郭勒市| 宁阳县| 横山县| 刚察县| 平邑县| 怀宁县| 阳朔县| 枞阳县|