문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top