简体   繁体   English

将状态传递给CDI容器管理的bean

[英]Passing state to CDI-container-managed beans

I'm using Spring for this project, but I've had the same problem with Guice as well. 我在这个项目中使用Spring,但是Guice也遇到了同样的问题。

Basically, I have functionality that requires both stateless helpers and state data to operate on. 基本上,我具有需要无状态助手和状态数据才能运行的功能。

public class AwesomeDoer {
    @Inject
    private Helper helper; //stateless
    ...
    public void doAwesome(int state) {
        helper.help(state)
    }

}

This looks pretty good, until doAwesome has 5 parameters and is being called 1000 times, but 3 of the arguments are the same value every time while a fourth argument might change only a handful of times. 直到doAwesome有5个参数并被调用1000次,这看起来还是不错的,但是每次3个参数都是相同的值,而第四个参数可能只改变了几次。 Changing the appropriate parameters to fields is the obvious solution. 将适当的参数更改为字段是显而易见的解决方案。 However, this requires you to sacrifice either the CDI management of this class, or else you have to have an initializer or setters to fill in the state after Spring does its thing. 但是,这需要您牺牲此类的CDI管理,否则必须在Spring完成其工作后必须具有一个初始化器或设置器来填充状态。

I've usually gotten around this by creating a factory managed by Spring, ie 我通常通过创建一个由Spring管理的工厂来解决这个问题,即

public class AwesomeFactory {
    @Inject
    private Helper helper;

    public AwesomeDoer getAwesomeDoer(int state) {
        return new AwesomeDoer(helper, state);
    }
}

But again, this means that my AwesomeDoer is no longer being managed by Spring, and it requires me to write yet another layer of non-business logic. 但是再次,这意味着我的AwesomeDoer不再由Spring管理,并且它要求我编写另一层非业务逻辑。 It's also easy to imagine this approach leading to the creation of an AwesomeFactoryFactory, etc, which always makes me die a little on the inside. 也很容易想象这种方法会导致创建AwesomeFactoryFactory等,这总是使我在内部有些丧命。

So does anybody have a cleaner way of doing this? 那么,有人能做到这一点吗?

You can mark your bean using @Configurable from Spring and create it using new AwesomeDoer and passing the parameters in your constructor. 您可以使用Spring的@Configurable标记bean,并使用new AwesomeDoer并在构造函数中传递参数来创建它。 @Configurable makes you create the bean on demand and the bean will be managed by Spring to fire the injections like @Autowired . @Configurable使您可以按需创建Bean,Spring将管理该Bean来触发@Autowired之类的注入。

More info: Create a bean using new keyword and managed by Spring , check the section at the bottom. 更多信息: 使用new关键字创建一个bean,并由Spring管理 ,检查底部的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM