开发者

What is the proper idiom for using the built in Guice Injection for annotating static java.util.Logger instances?

I want to start using Guice 3.x to magically inject my java.util.logging.Logger instances.

Here is a snippet of code I am trying to get to work:

@Singleton
public class Main
{
    @Inject
    private static final Logger logger;

...
}

This doesn't seem to work.

I get Exception in thread "main" java.lang.NullPointerException no matter what scope I use on the declaration.

I added the line super.requestStaticInjection(Main.class); to my module in the configure() method and it started working, but only if I remove the final keyword and make it static Logger logger.

I would pr开发者_开发技巧efer to keep the Logger final if at all possible.

What is the proper idiomatic Guice way of doing this?


You can inject into static properties in guice with e.g.

class Dummy {
   @Inject static Foo;
}

and

requestStaticInjection(Dummy.class);

in the injector configureModule.


Guice does allow final field injections, however it's not recommended

The binding's value is set into the field. Injecting final fields is not recommended because the injected value may not be visible to other threads.

source, also be avare of all the caveats of set().

This means you can have a final field, but not a static final field injected.

If the underlying field is final, the method throws an IllegalAccessException unless setAccessible(true) has succeeded for this field and this field is non-static.

On the other hand JSR 330 does not allow injection of final fields.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜