Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Guice without a main method

I'm creating a library that will be included as a jar, so it won't contain a main method. I'm wondering what is the best practice for bootstrapping Guice in this case. I have one top level singleton.

public class TestManager
{
    private TestManager()
    {
    }

    public static TestManager getInstance()
    {
        // construct and return singleton
    }

    public void createSomeObjects()
    {
    }

}

Where should I bootstrap Guice? I was thinking that in the constructor that I could call Guice.createInjector(new Module()); but it wouldn't inject any of the objects created in createSomeObjects().

Is there a common way to do this when you don't have a main method()?

Cheers.

like image 669
marchaos Avatar asked Sep 29 '10 12:09

marchaos


People also ask

Is Guice a provider Singleton?

Guice comes with a built-in @Singleton scope that reuses the same instance during the lifetime of an application within a single injector. Both javax. inject. Singleton and com.

Does Google use Guice?

Guice is an open source, Java-based dependency injection framework. It is quiet lightweight and is actively developed/managed by Google.

What is the point of Guice?

Guice solves the problem of having two different String objects you want to inject through "named annotations". You can bind these manually in your module, but there are libraries which will pull these from your configuration that make use of Names.

Can Guice inject null?

Guice forbids null by default So if something tries to supply null for an object, Guice will refuse to inject it and throw a NULL_INJECTED_INTO_NON_NULLABLE ProvisionException error instead. If null is permissible by your class, you can annotate the field or parameter with @Nullable .


1 Answers

Much like logging configurations, if this is a true library then your options are pretty much this:

  • Tell the library user that they are responsible for bootstrapping Guice themselves.
  • Provide a library initialization method that takes care of bootstrapping Guice if they want to use your library

Trying to make the library super-smart to do self-configuration often ends up with somewhat inflexible, hard to test class hierarchies.

like image 143
Ophidian Avatar answered Oct 19 '22 02:10

Ophidian