FAQ Database Discussion Community


How to use Guice Module to instantiate one of multiple fields in a class?

java,constructor,dependency-injection,guice
I have a class, and create an instance using a regular constructor: class Foo { String fooName; Bar barObject; ExternalService externalService; Foo(String fooName, Bar barObject, Service someService){ this.fooName = fooName; this.barObject = barObject; this.externalService = externalService; //call to super } } class MyApplication { //instantiate ExternalService ... Foo foo =...

Error running tests in Play Framework after migrating to 2.4.x (Java)

java,playframework,guice,webjars,playframework-2.4
I just migrated from 2.3 to 2.4. The application itself seems to be working, but none of the tests will run. They all fail with the following error: [error] Test models.TestCountry.createTheater failed: com.google.inject.ProvisionException: Unable to provision, see the following errors: [error] [error] 1) Error injecting constructor, java.lang.IllegalStateException: Got deeper than...

Error in binding: No implementation was bound - Guice

java,guice
I’m trying to use Guice to solve dependency. I’ve read through tutorials and examples, but I still can’t figure out why I keep getting this error: No implementation for com.edit.owl.persistence.PersistentStore<com.edit.common.domain.Foo> annotated with @com.google.inject.name.Named(value=FooPersistence) was bound. while locating com.edit.owl.persistence.PersistentStore<com.edit.common.domain.Foo> annotated with @com.google.inject.name.Named(value=FooPersistence) for parameter 0 at...

Guice inject based on annotation value

java,annotations,guice,inject
I would like to use goolge/guice inject a value based on a class i provide with the annotation. AutoConfig annotation @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.PARAMETER, ElementType.FIELD }) public @interface AutoConfig { // default null not possible Class<? extends Provider<? extends ConfigLoader<?>>> provider() default XMLAutoConfigProvider.class; } This is my annotation which allows...

Guice Provider vs EntityManager

java,jpa,guice,guice-servlet,guice-persist
I was trying to get simple webapp working with Guice and JPA on Jetty, using the persistence and servlet guice extensions. I have written this Service implementation class: public class PersonServiceImpl implements PersonService { private EntityManager em; @Inject public PersonServiceImpl(EntityManager em) { this.em = em; } @Override @Transactional public void...

How inject generic interface implementation with guice

java,generics,dependency-injection,guice
aI would like to be able to inject an implementation of a generic interface using Guice annotation Let me show you my code : public interface A<T>{ } public abstract class B<T> implements A<T>{ } public class C extends B<T> { } So i create an annotation MyAnnotation and now...

Is there an equivalent of Guice Providers in Simple Injector?

java,c#,dependency-injection,guice,simple-injector
Is there an equivalent injecting Guice Providers in Simple Injector? I need to inject a dependency into a constructor that will let me create as many instances of a dependency as needed. In guice it would look like this... public class RealBillingService implements BillingService { private final Provider<CreditCardProcessor> processorProvider; private...

Guice: instantiating a singleton before creating the module

java,dependency-injection,guice
Is it possible to instantiate and assign a singleton to a reference with Guice before creating the Module and pass that instance to the Module constructor be bound during configuration? Here is an example of what I mean: I have a method that allows me to create objects depending on...

bootstrapping guice injector

java,guice
I have a scenario where I will need some objects injecting at the start like logging, but then other objects injected on demand. What I don't know is if in my console application, do I just call Guice.createInjector(....) in my Main function and then when I need another object, the...

Injecting dependency with Guice in non-constructor method

java,mocking,tdd,guice,roboguice
I'm working on a component that creates HTTP requests dynamically, and I'd like to be able to mock those requests for unit testing. Currently the implementation looks something like this: class ModelClass { public void populate() { HTTPRequest request = new HTTPRequest(); //configure request... request.send(); } } Is there a...

Jersey resource that matches any path

java,servlets,guice,jersey-1.0
I am using Jersey v1.x and a Guice Servlet. What I'm trying to do is bind a Jersey Resource that matches any @Path, such that I can use Jersey to respond with a 404. I'm looking to do this, since my servlet consists of different components (e.g. a rest API...

gae session data not updated

google-app-engine,guice
I'm using guice 4.0 on current java app engine and have the problem that changes to my @SessionScoped classes are not persisted (on the production system). After initialising the session objects, changes are not persistend.

Guice: Using providers to get multiple instances:

java,dependency-injection,guice
I am trying to learn Guice for dependency Injection using Providers to create multiple instances of an object(Example from getting started guide on Guice website). how should I test this? Please advise. The following is the module: package testing; import com.google.inject.AbstractModule; public class BillingModule extends AbstractModule { @Override protected void...

How to annotate injector.getInstance?

java,junit,dependency-injection,guice
I want to inject an instance from Guice injector in my unitTest. Which diffrentiator can I use? I know @annotation mechanism is used in ctor params but junit doesn't allow ctor with params. should I use class fields' @annotation? public void setUp() throws Exception { RoutingResponseRepository routingResponseRepository = injector.getInstance(RoutingResponseRepository.class); }...

Is it possible to inject value to modules

java,dependency-injection,guice
I have a Module that uses a flag to decide whether or not to install another module. Is there a way to achive that by injection, or do I need to explicitly pass the flag's value in the ctor? public class MyModule implements Module { private final Boolean shouldInstallOtherModule; @Inject...

Empty Multibinder/MapBinder in Guice

java,plugins,dependency-injection,guice
In the process of building a plugin architecture using Guice's MapBinder, using Guice 3.0, I've run into the issue that Guice throws a CreationException when stripped of all modules, which is a viable configuration in this application. Is there a way to get Guice to inject an empty Map? Or,...

Guice Singleton Static Injection Pattern

java,dependency-injection,guice
I'm new to Google Guice and understand Dependency Injection conceptually, but am running into issues trying to incorporate it into my application. My specific question is around Singleton objects. Here's an example: First, my Module class, which binds a heavy Singleton Connection interface to its implementation. public class MyModule extends...

guice injection in static variable

java,guice,guice-3
I Have doubt about guice injection. Is it possible to inject a @named variable value to a static variable? I have tried @Provides @Named("emp.id") public Integer getEmpId() { return 2; } and tried to inject this value to static variable such as @Inject @Named("emp.id") private static Integer id; But the...

Guice Names.bindProperties(binder(), properties) on output of a module?

properties,guice
I use an external service to provide properties, but want to make those properties available as @Named(..) vars. Trying to do this in a configure method fails with npe: Names.bindProperties(binder(), myPropRetriever.getProperties()); is failing because the myPropRetriever isn't appearing until guice has done it's work. I can see why this makes...

Inject Guice on a static final property?

guice
I have many named annotated instances of a TabularResultSet class I want to pass to multiple classes to a static final property. How do I inject this? I dont think it is liking the final and static nature of the property. Must I call the injector directly in the property...

Google Guice bind by annotation and/or package

java,dependency-injection,guice
I have 3 beans in one package that I would like to be eager singletons. public class Module1 implements Module { @Override public void configure(Binder binder) { binder.bind(Bean1.class).asEagerSingleton(); binder.bind(Bean2.class).asEagerSingleton(); binder.bind(Bean3.class).asEagerSingleton(); } } How can I configure them all as eager singletons without exact writing class name using Google Guice? I'm...

Inject values of a Map with Guice

java,dependency-injection,guice
I have a Guice managed service that injects a couple of other services. The other services are used depending on a key value that is passed to my service method. So I want to make a Map that maps the service to use to the corresponding key: @Inject private IServiceA...

Using non-static injected services in JUnit Parameterized Tests

java,junit,guice
I want to use Guice and GuiceBerry to inject a non-static legacy service into a factory class. I then want to inject that factory into my Parameterized JUnit test. However, the issue is JUnit requires that the @Parameters method be static. Example factory: @Singleton public class Ratings { @Inject private...

Modern Akka DI with Guice

java,akka,guice
Java 8, Guice 4.0 and Akka 2.3.9 here. I am trying to figure out how to annotate my actor classes with JSR330-style @Inject annotations, and then wire them all up via Guice. But literally every single article I have read (some examples below) either uses Scala code examples, a criminally-old...

Guice and restricting clients to getting only certain instances

java,guice,hexagonal-architecture
When using Guice, how to restrict clients to getting instances from a specific group of classes (aka the Facebook problem)? Imagine I architect my system using ports-and-adapters and I have an admin adapter side, a business logic component, and a data-access side used by the business component. How to allow...

How to mock an Authenticator in play framework with guice injections?

java,playframework,playframework-2.0,guice,guice-3
I have a play application with authenticated routes. I implemented an Authenticator, storing users into elasticsearch. My securized methods in my controllers are annotated with the @Security.Authenticated annotation. For my unit tests with mockito, I would like to mock this class but I don't know how to do this. I...

Java - How to log metrics from a ThreadPool?

java,logging,threadpool,guice
I wrapped a ThreadPoolExecutor in an implementation of ExecutorService of my own, just to send it any filesystem writing task, so they would be treated sequencially and one-by-one. (No need to harass this poor disk writing head.) The wrapper comes in handy by: allowing me to Inject this ThreadPool as...

Inject a TypeListener

java,guice
I have this scenario where I want to inject a TypeListener with dependencies, but it will never work because the TypeListener is used to actually perform the injection. How can I get this thing done? Is there a guicey-way? Notes: I'm using Guice 4.0 MyManager will be used after Guice::createInjector....

Guice: @Provider vs toProvider binding [duplicate]

java,dependency-injection,guice
This question already has an answer here: Guice @Provides Methods vs Provider Classes 1 answer Trying to understand dependency injection using Guice. In which cases do we use @Provides and which ones do we use the toProvider binding in the module?...

injector.getInstance of a generic type

java,class,generics,dependency-injection,guice
I have seen this post about registering generic type. example on how to register: bind(new TypeLiteral<Dal<RoutingResponse>>() {}).to((Class<? extends Dal<RoutingResponse>>) ResponseDal.class); however how can I get an instance of a generic type from the injector? I have tried: injector.getInstance(Dal<RoutingResponse>().getClass()); but got compilation error. How should I write this?...

How inject 3 instances of same type with different dependence by Guice?

spring,dependency-injection,guice,guice-3
I am using Guice to manager my class dependence. I have a LogicHandler class which depended on several Components class. public interface LogicHandler { private Component component1; private Component component2; private Component component3; } public interface Component { public String doWork(); } I will have 3 instances of LoigcHanlder. Using...

Guice @Provides Methods vs Provider Classes

java,dependency-injection,guice,roboguice
I'm working on a fairly large project that has a lot of injections. We're currently using a class that implements Provider for each injection that needs one, and they mostly have one line get methods. It's starting to get annoying to create a new class every time I need a...

Does guice allow injectMembers into a constructor?

java,constructor,guice,inject
My problem is here; I don't know if i can do that with guice: public class Foo { private final Bar bar; @Inject public Foo(Injector injector) { this.bar = new Bar(); injector.injectMembers(bar); } } *bar will be injected correctly or not ? Thank you...

Get implementations off a MapBinder in Guice

java,guice
Basically I want to understand how the MapBinder works. I tried to search for example but couldn't find one that satisfied me. Before my question, here is some of my setup. public class MyModule extends AbstractModule { @Override protected void configure() { MapBinder<String, MyInterface> binder = MapBinder.newMapBinder(.....); binder.addBinding("one", One.class); binder.addBinding("two",...

Difference between @inject and @mock annotations

gwt,junit,mockito,guice,gin
In the Context of JUnit, what is the difference between @inject and @mock, and in which conditions both can be used? thanks, Rohit...

Guice : Inject an ArrayList of Strings

java,arraylist,guice,inject
I'm trying to inject an ArrayList of Strings with the help of Guice. I want to show a panel with many RadioButtons (for example) where an user can select some services to activate. Once selected, I would like to get all the names of the selected services and add them...

Is there a way to bind a couple of instances to many different keys in Guice?

java,collections,guava,guice
We need to create some mapping between many types of some object, described with enum values: public enum ObjectType { Type1,Type2,Type3,Type4,Type5...TypeN } ... and several instances of strategies to use for these types or, for example, boolean values which relate to the mentioned ObjectTypes A MapBinder from Guice can be...

Dropwizard 0.8 and GuiceBundle Governator: Forcing Resources class to be Singleton

java,guice,dropwizard
I'm using Dropwizard 0.8.1 and I have observed that resource object is created each time a belonging path is called. I think this done because the resource are registered by class when the application is bootstraped. Is there anyway to force the resources to be Singleton? I have tried to...

Guice / DI and mixing injection and parameters passed in at runtime

java,dependency-injection,guice
I have a situation where when I initialize some of my classes, some of the fields I need to be injected (e.g. references to factories etc) whereas some others are dynamic and created at runtime (e.g. usernames etc). How do I construct such objects using the GUICE framework? Simply annotating...

Unable to inject using guice

guice
I have an archive class having the following structure: public class Archive implements Tasklet, StepExecutionListener{ @Inject private Configuration configuration; public static final String FF = "ff"; @Override public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception { System.out.println("in execute method :)"); return RepeatStatus.FINISHED; } @Override public ExitStatus afterStep(StepExecution arg0) { return...

Create and initialize a singleton with Guice [duplicate]

java,guice
This question already has an answer here: Guice: How to get instance of Singleton without injector or using Constructor Injection 1 answer I have a the following classes StorageProxy.java (Interface) StorageProxyImpl1.java (Implementation1 of StorageProxy Interface) public class StorageProxyImpl1 extends StorageProxy{ public void init(String key){ .... } } public class...

Why is a lambda expression breaking guice error handling when i try to start jetty?

java,lambda,java-8,guice,guice-3
I face the following problem where i try to start jetty, i get the following exeption: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.17:test failed: There was an error in the forked process [ERROR] org.apache.maven.surefire.testset.TestSetFailedException: java.lang.RuntimeException: com.google.inject.internal.util.$ComputationException: java.lang.ArrayIndexOutOfBoundsException: 51966 [ERROR] at...