Weld CDI自定义范围中的种子值

问题描述 投票:7回答:1

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

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

我想通过注册一个从AbstractBoundContext获取值的Bean可以做到这一点,但是从自定义范围中播种一个值的例子似乎很难找到。如何创建一个自定义范围,该范围可以为可以注入其他位置的值提供种子?

编辑:我目前正在使用以下解决方法,可以在拦截器中注入以在进入范围时设置Configuration,然后可以通过其线程本地提供程序注入。我仍在寻找感觉不那么hacky /与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);
    }    

}
cdi weld weld2
1个回答
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有一个非常复杂的例子

© www.soinside.com 2019 - 2024. All rights reserved.