CDI扩展,更改处理的类型 [英] CDI extension, altering processed type

查看:104
本文介绍了CDI扩展,更改处理的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Weld 1.1.13。最终与Arquillian进行了测试。

Using Weld 1.1.13.Final in test with Arquillian....

假设我向某个领域注入了一些不稳定的东西。我希望拥有注入点的bean可以接收更改事件,例如需要更改的属性。考虑创建CDI扩展。

Let's say I inject into a field something volatile. Something like a property subject to change that I want the bean owning the injection point to receive change events. Thought about creating a CDI extension.

捕获到ProcessAnnotatedType事件,并查找在字段注入点上具有自定义注释的所有字段:

Caught ProcessAnnotatedType event and looking for all fields that have an custom annotation on field injection points:

 <T> void pat(@Observes ProcessAnnotatedType<T> event, BeanManager bm) {
   final AnnotatedType<T> target = event.getAnnotatedType();

   for (AnnotatedField<? super T> field : target.getFields())
     if (field.isAnnotationPresent(Value.class)) {  // ignore that I don't check @Inject here for the moment
        CtClass wrapper = pool.get(target.getJavaClass().getName());
        ConstPool cp = wrapper.getClassFile().getConstPool();

        CtMethod m = CtNewMethod.make(....)
        ....
        wrapper.addMethod(m);

        event.setAnnotatedType(bm.createAnnotatedType(wrapper.toClass()));
     }
 }

此后甚至还抢夺了油田和油田的所有注入点用与包装类型相对应的新字段替换了基础的WeldField。否则,bean验证将失败。

Had even grabbed thereafter all the injection points for fields and replaced the underlying WeldField with a new Field corresponding the "wrapper" type. Otherwise bean validation fails.

但这仅适用于启动过程中的东西设置,例如当Arquillian使用Bean Manager初始化一个注入了我的包装的类时,这种方法就不起作用。 。由于Bean解析程序使用Type作为哈希键来查找bean,因此事情失败了。

But this only works for stuff setup during startup not when for example Arquillian uses the Bean Manager to initialize a class that injects one of my "wraps". Things fail since the Bean Resolver uses the Type as a hash key to find beans.

基本上,我不认为我可以屏蔽带有注释的类(由CDI使用一种额外的方法来接收自定义事件。本来很酷,但类型就是类型(即不知道如何代理或伪造equals / hashCode)。

Basically I don't think I can "mask" a class that is annotated (made into a bean) by the CDI with an extra method to receive custom events. Would have been cool but a Type is a Type (i.e. no idea how to proxy or fake the equals/hashCode).

推荐答案

得到它了。事实证明,TypeSafeBeanResolver解析器(至少是CDI Weld实现)中的计算值函数(google扩展名)很聪明。如果我只是扩展类:

Got it. Turns out the compute value function (google extension) inside the TypeSafeBeanResolver resolver (at least the CDI Weld implementation) is smart. If I just extend the class:

 CtClass wrapper = pool.makeClass(target.getJavaClass().getName()+"Proxy");
 wrapper.setSuperclass(pool.get(target.getJavaClass().getName()));
 .....
 final AnnotatedType<T> other = bm.createAnnotatedType(wrapper
                    .toClass());

然后一切正常。测试了在bean中捕获事件。将把代码发布在要点上并带有注释。

then everything works fine. Tested capturing an event in a bean. Will post the code on a Gist with a comment.

这篇关于CDI扩展,更改处理的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆