Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mimicking Spring profiles in Guice

Tags:

java

guice

In Spring, if I want to have one set of objects for production, and another for local development/testing. I could use the @Profile annotation to designate the different classes, and switch between them by providing a system property when starting the app.

Is there anything like this in Guice, or do I need to manually check some property myself and load a different set of modules when bootstrapping my Injector?

like image 879
Thorn G Avatar asked Aug 07 '13 19:08

Thorn G


People also ask

Does Guice work with spring?

Guice manages its dependencies in a special class called a module. A Guice module has to extend the AbstractModule class and override its configure() method. Guice uses binding as the equivalent to wiring in Spring. Simply put, bindings allow us to define how dependencies are going to be injected into a class.

Which is better Guice or Spring?

Spring allows you to omit the @Autowired annotation when there's only one constructor. Guice allows binding to a Provider, as well as injecting a Provider of your class, even when your class has no Provider binding.

What does @provides do in Java?

Dependency Injection for Java Developers with Dagger & Guice Guice provides a way to create bindings with complex objects using @provides method. This methods is being part of Binding Module and provides the complex object to be mapped.

What is binding in Guice?

A binding is an object that corresponds to an entry in the Guice map. You add new entries into the Guice map by creating bindings.


1 Answers

You'll need to identify the environment yourself, and choose which modules to apply in which environment, but you do have access to Modules.override to specifically override certain bindings without having to create a lot of module variants. Use it judiciously—it's very easy to get your modules tangled if you override many bindings or in unpredictable places.

like image 121
Jeff Bowman Avatar answered Sep 21 '22 06:09

Jeff Bowman