简体   繁体   中英

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.

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

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

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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