将状态传递给CDI容器管理的bean [英] Passing state to CDI-container-managed beans

查看:75
本文介绍了将状态传递给CDI容器管理的bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个项目中使用Spring,但是Guice也遇到了同样的问题。

I'm using Spring for this project, but I've had the same problem with Guice as well.

基本上,我有需要两个无状态助手的功能

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

}

这看起来还不错,直到 doAwesome 有5个参数并且是被调用了1000次,但其中的3个参数每次都具有相同的值,而第四个参数可能只改变了几次。将适当的参数更改为字段是显而易见的解决方案。但是,这需要您牺牲此类的CDI管理,否则必须在Spring完成其操作后必须使用初始化程序或设置程序来填充状态。

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. 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.

我通常通过创建一个由Spring管理的工厂来解决这个问题,即

I've usually gotten around this by creating a factory managed by Spring, ie

public class AwesomeFactory {
    @Inject
    private Helper helper;

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

但是再次,这意味着我的AwesomeDoer不再由Spring管理,这需要我编写另一层非业务逻辑。也很容易想象这种方法会导致创建AwesomeFactoryFactory等,这总是使我在内部变得有些丧气。

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. 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.

所以有人有一种更清洁的方法吗?

So does anybody have a cleaner way of doing this?

推荐答案

您可以使用 @Configurable 标记您的bean。从Spring并使用 new AwesomeDoer 创建它,并在构造函数中传递参数。 @Configurable 使您可以按需创建Bean,Spring将管理该Bean触发诸如 @Autowired 的注入。

You can mark your bean using @Configurable from Spring and create it using new AwesomeDoer and passing the parameters in your constructor. @Configurable makes you create the bean on demand and the bean will be managed by Spring to fire the injections like @Autowired.

更多信息:使用 new创建一个bean 关键字并由Spring管理,请检查底部的部分。

More info: Create a bean using new keyword and managed by Spring, check the section at the bottom.

这篇关于将状态传递给CDI容器管理的bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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