我将 JSF 2.1 与 CDI 和 JBoss 7.1.1 结合使用
是否可以在父类(super class)变量principal
中注入(inject)CDI并强制转换为派生类?在示例中,MyUserPrincipal
是派生类。如果我写@InjectPrincipalprincipal,我从调试(和重载的toString()方法)知道,MyUserPrincipal
代理类将被注入(inject)到变量principal
中。但我无法将此实例转换为 MyUserPrincipal
实例。
下面是我解决问题的两次尝试:
public class MyUserPrincipal implements Principal, Serializible{
MyUserPrincipal (String name){
}
public myMethod() { }
}
//Attempt 1:
public class MyCdiClass2 implements Serializable{
//MyUserPrincipal proxy instance will be injected.
@Inject Principal principal;
@PostConstruct init() {
MyUserPrincipal myPrincipal = (MyUserPrincipal) pincipal; //<--- Fails to cast! (b)
myPrincipal.myMethod();
}
}
//Attempt 2:
public class MyCdiClass1 implements Serializable{
@Inject MyUserPrincipal myPrincipal; //<---- Fails to inject! (a)
@PostConstruct init() {
//do something with myPrincipal
}
}
最佳答案
如果您没有生产者,那么您注入(inject)的实际上是一个代理,它扩展了容器提供的主体。实现相同接口(interface)的两个类与类型为该接口(interface)的字段的赋值兼容,但不能将其中一个转换为另一个。
也就是说,您似乎想要覆盖内置的主体 bean。据我所知,您只能使用 CDI 1.0 之前的替代方案以及使用 CDI 1.1 中的装饰器来实现这一点,请参阅 CDI-164 .
替代方案示例:
package com.example;
@Alternative
public class MyUserPrincipal implements Principal, Serializible {
// ...
@Override
public String getName() {
// ...
}
}
// and beans.xml
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"> com.example.MyUserPrincipal
装饰器示例:
@Decorator
public class MyUserPrincipal implements Principal, Serializible {
@Inject @Delegate private Principal delegate;
// other methods
@Override
public String getName() {
// simply delegate or extend
return this.delegate.getName();
}
}
// again plus appropriate beans.xml
关于java - 如何在 CDI 注入(inject)的字段中从父类(super class)转换为派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18447310/