【问题标题】:Seed value in Weld CDI custom scopeWeld CDI 自定义范围中的种子值
【发布时间】:2016-11-14 06:19:24
【问题描述】:

来自 Guice 背景,我知道可以使用从作用域中播种对象值。

  scope.seed(Key.get(SomeObject.class), someObject);

我想可以通过注册一个从AbstractBoundContext 获取值的 Bean 来做到这一点,但是仅从自定义范围播种一个值的示例似乎很难找到。如何创建一个自定义范围来植入可以在其他地方注入的值?

编辑: 我目前正在使用以下解决方法,可以在进入范围时注入拦截器以设置Configuration,然后可以通过其线程本地提供程序注入。不过,我仍在寻找那些感觉不那么老套/与 Weld 中的范围/范围上下文系统更集成的选项。

@Singleton
public class ConfigurationProducer {

    private final InheritableThreadLocal<Configuration>  threadLocalConfiguration =
    new InheritableThreadLocal<>();

    @Produces
    @ActiveDataSet
    public ConfigurationConfiguration() {
       return threadLocalConfiguration.get()
    }

    public void setConfiguration(Configuration configuration) {
         threadLocalConfiguration.set(configuration);
    }    

}

【问题讨论】:

  • guice 中的 Seed 函数只是使用 Map 来存储您的对象。在 CDI 中,如果你想要一个自定义范围,你可以编写一个扩展并实现 Scope 接口。您所有的种子对象都可能会放置在某些 Map 中的上下文接口实现中。
  • 是的,我发现了范围注释和扩展。然而,我想知道应该如何实现 javax.enterprise.context.spi.Context。以及如何从 Contextual 到 Guice 中的 Key。
  • 您能否详细说明您需要的自定义范围以及您想要实现的目标?内置范围还不够吗?
  • 我正在尝试将其用于多租户环境,我正在创建一个@TenantScoped,其中@TenantScoped EntityManger 绑定到使用为该租户配置的EntityManagerFactory 的提供程序.所以当进入作用域时,我需要能够传递一个对象引用,稍后可以注入一个特定的键/限定符。
  • 不,它甚至可以是一个常量字符串或 POJO

标签: cdi weld weld2


【解决方案1】:

答案是使用 AfterBeanDiscovery 事件注册一个自定义 bean,如下所示:

    event.addBean()
        .createWith(ctx -> commandContext.getCurrentCommandExecution())
        .addType(CommandExecution.class)
        .addQualifier(Default.Literal.INSTANCE)
        .scope(CommandScoped.class)
        .beanClass(CommandExtension.class);

https://github.com/weld/command-context-example 上有一个非常复杂的示例

【讨论】:

    猜你喜欢
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 2016-02-14
    • 2010-12-03
    • 2016-11-18
    • 1970-01-01
    相关资源
    最近更新 更多