Weld CDI自定义范围中的种子值 [英] Seed value in Weld CDI custom scope

查看:90
本文介绍了Weld CDI自定义范围中的种子值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Coming from a Guice background, I know that it is possible to seed an object value from a scope using.

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

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

I suppose one could do this by registering a Bean that gets a value from an AbstractBoundContext, but examples just seeding one value from a Custom Scope seem hard to find. How do I create a custom scope that seeds a value that can be injected elsewhere?

编辑:
我目前正在使用按照以下解决方法,可以在进入范围时将其注入拦截器以设置 Configuration ,然后可以通过其线程本地提供程序注入。不过,我仍在寻找不易破解的选项/与Weld的范围/作用域上下文系统更好地集成。

I am currently using the following workaround, that can be injected in an interceptor to set the Configuration when entering the scope, and can then be injected through its thread local provider. I am still looking for options that feel less hacky / are more integrated with the scope/scope context system in Weld though.

@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);
    }    

}


推荐答案

答案是使用AfterBeanDiscovery事件注册自定义bean,例如:

The answer is to register a custom bean with the AfterBeanDiscovery event, like so:

    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

这篇关于Weld CDI自定义范围中的种子值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆