2013-08-26 27 views
1

我正在使用JSF 2.1与CDI和JBoss 7.1.1如何从超类转换为由CDI注入的字段中的派生类?

是否可以将CDI注入超类变量principal并转换为派生类?在示例MyUserPrincipal是派生类。如果我编写@Inject Principal principal我知道从调试(和重载toString()方法)MyUserPrincipal代理类将被注入变量principal。但我无法将此实例投射到MyUserPrincipal实例。

下面我2次尝试解决问题:

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 

    } 
} 
+0

您是否有MyUserPrincipal的生产者方法? –

+0

不,MyUserPrincipal正在启动从登录容器类(UsernamePasswordLoginModule)衍生而来,并来自登录容器(JBoss-Authentication)。 – Tony

回答

1

如果你没有一个制片人,你要注入实际上是扩展了容器提供主要的代理。实现相同接口的两个类与赋予该接口类型的字段的赋值兼容,但不能将其中一个赋值为另一个。

这就是说,它似乎你想覆盖内置的主要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 
+0

谢谢你的回答!我会尝试。 – Tony