【问题标题】:How to cast from super class to derived class in field injected by CDI?如何在 CDI 注入的字段中从超类转换为派生类?
【发布时间】:2013-08-29 03:08:09
【问题描述】:

我将 JSF 2.1 与 CDI 和 JBoss 7.1.1 一起使用

是否可以在超类变量principal 中注入 CDI 并转换为派生类?例如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

   }
}

【问题讨论】:

  • 你有 MyUserPrincipal 的生产者方法吗?
  • 不,MyUserPrincipal 是从登录容器类(UsernamePasswordLoginModule)派生的初始化并来自登录容器(JBoss-Authentication)。

标签: java dependency-injection jboss7.x cdi inject


【解决方案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

【讨论】:

  • 感谢您的回答!我会试试的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-12
  • 2017-01-08
  • 2010-11-01
  • 2013-11-17
相关资源
最近更新 更多