JavaEE 6 Study

关于CDI 的 inject。

在java 官方的陈述中, 要用inject, 需要满足以下的条件:

1.To use @Inject, the first thing you need is a META-INF/beans.xml file in the module or jar。

注意的是,所谓的inject, 只有在container 中谈才有意义,离开容器,就没有用武之地了。

关于 CDI Interceptor。

CDI Interceptor 注解的基本用法:

1.创建注解
@InterceptorBinding
@Target({ TYPE, METHOD })
@Retention(RUNTIME)
public @interface Log {
}

2.创建 Interceptor class:

@Interceptor
@Log  //binding the interceptor here. now any method annotated with @Log would be intercepted by logMethodEntry
public class LoggingInterceptor {
    @AroundInvoke
    public Object logMethodEntry(InvocationContext ctx) throws Exception {
        System.out.println("Entering method: " + ctx.getMethod().getName());
        //or logger.info statement
        return ctx.proceed();
    }
}

以上两步注意 @InterceptorBinding,  @AroundInvoke and @Interceptor 的用法。

3. 使用这个注解在其他地方,用在class 和 method 上。

4. 启用拦截器:
<beans>
  <interceptors>
    <class>org.superbiz.cdi.bookshow.interceptors.LoggingInterceptor
    </class>
  </interceptors>
</beans>

关于CDI @RequestScoped

对于requestScoped 的对象,每次请求都会生成一个对象。
“This means that an instance will be created only once for every request and will be shared by all the beans injecting it.”

关于 @ApplicationScoped

对于 @ApplicationScoped 对象,每个application 只会生成一个对象。
An object which is defined as @ApplicationScoped is created once for the duration of the application.

猜你喜欢

转载自dzhxie.iteye.com/blog/2288032
今日推荐