CDI: How to take care of beans configuration?
In CDI, how do I configure my beans?
Let's say I have this code:
class JawaBotApp {
private void init( String configFilePathString ) throws JawaBotException {
ConfigBean cb = new JaxbConfigPersister(configFilePathString).load();
JawaBotApp.jawaBot = JawaBot.create( cb );
}
}
class JawaBot {
public static JawaBot create( ConfigBean cb ) throws JawaBotException{
JawaBot bot = new JawaBot();
bot.applyConfig(cb);
bot.init();
return bot;
}
}
How would I convert it so both could be CDI beans?
I thought about annotating the create()
with @Produces
, howeve开发者_运维问答r that would need to have it non-static, and rewrite it so the ConfigBean gets injected, which would need to rewrite JaxbConfigPersister
or create a wrapper object... Too much work for nothing.
Is there better approach?
Something like:
class JawaBot {
@Inject public JavaBot(@JawaConfig String configFilePathString) {
...
}
}
Then you just need to produce an @JawaConfig String somewhere which represents your configuration. This could then be mocked out with something like an alternative or specialize to give you a diff config, or just some silly little @Producer that looks at some other external file/setting.
Then you just @Inject a JawaBot when you want it instead of all the other setup, and everything just lives in the injected constructor.
精彩评论