如何在CDI注入的字段中从超类转换为派生类



我使用带有CDI和JBoss 7.1.1 的JSF 2.1

是否可以在超类变量principal中注入CDI并强制转换为派生类?在示例中,MyUserPrincipal是派生类。如果我写@Inject Principal principal,我从调试(并重载到String()方法)中知道MyUserPrincipal代理类将被注入变量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
   }
}

如果您没有生产者,那么您注入的实际上是一个扩展容器提供的主体的代理。实现同一接口的两个类与类型为该接口的字段的赋值兼容,但不能将其中一个强制转换为另一个。

也就是说,您似乎想要覆盖内置的主bean。据我所知,您只能使用CDI1.0之前的替代方案,以及CDI1.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

最新更新