Menu
  • HOME
  • TAGS

Can we use Google Guice DI with a Scala Object instead of a Scala class in Play 2.4 with scala

scala,playframework,guice,ehcache

No, it is not possible to inject objects in guice. Make your SampleDAO a class instead, where you inject CacheApi. Then inject your new DAO class in your controllers. You can additionally annotate SampleDAO with @Singleton. This will ensure SampleDAO will be instantiated only once. The whole thing would look...

Inject a TypeListener

java,guice

I think at least some of the time (in tests or code analysis) type listeners have no cohesion to the types they are listening to, so there's no reason to have one injector. You'd use one injector to create the listener and one injector to create the code to be...

injector.getInstance of a generic type

java,class,generics,dependency-injection,guice

You can use Key to get instances of these bindings: injector.getInstance(Key.get(new TypeLiteral<Dal<RoutingResponse>>() {})); ...

Injecting dependency with Guice in non-constructor method

java,mocking,tdd,guice,roboguice

You can inject a provider which provides 'HTTPRequest' instances in your code. class ModelClass { @Inject Provider<HTTPRequest> httpRequestProvider; public void populate() { HTTPRequest request = httpRequestProvider.get(); } } Then, in your test code, you can mock the 'httpRequestProvider' to return mock 'HTTPRequest' instances. Provider<HTTPRequest> mockHttpRequestProvider = mock(Provider.class); when(mockHttpReqestProvider.get()).thenReturn(yourMockHTTPRequestObject); // Set...

Unable to inject using guice

guice

There's not enough information in your question to answer it, but I can give you some suggestions on where to look. Guice tries to prevent injection of null, so it's likely that Archive isn't getting injected at all. There are a couple of reasons that could happen: Archive has an...

Guice synthetic methods warning

java,jpa,aop,guice,shiro

The best way I could find is the following: just override the bindInterceptor methods like this. Matcher: public final class NoSyntheticMethodMatcher extends AbstractMatcher<Method> { public static final NoSyntheticMethodMatcher INSTANCE = new NoSyntheticMethodMatcher(); private NoSyntheticMethodMatcher() {} @Override public boolean matches(Method method) { return !method.isSynthetic(); } } The bindInterceptor method: @Override protected...

How to inject an Orika FactoryMapper impl using Google Guice?

guice,orika

In your Module, use bind() to register the built instance: bind(MapperFactory.class).toInstance(new DefaultMapperFactory.Builder().build()); or use a @Provides method: @Provides public MapperFactory mapperFactory() { new DefaultMapperFactory.Builder().build(); } with the first approach, you get a singleton, so every time you inject a MapperFactory, you get the same instance, in the second case, every...

Guice declerative vs method syntax

java,dependency-injection,guice

To no to() question, it's equivalent of bind(MySingleton.class).to(MySingleton.class), but this is done implicitly by guice. To test with guice, I personally use <dependency> <groupId>org.grouplens.common</groupId> <artifactId>common-test</artifactId> <version>0.4</version> </dependency> The code looks like this: @RunWith(GuiceTestRunner.class) @TestModule(CoreModule.class) public class EnvironmentSetupTest extends CamelTestSupport ...

GenericSignatureFormatError when mixing Guice and JMockit

guice,jmockit

This appears to be due to some invalid "generic info" inside the class generated by JMockit that implements the given interface. So, apparently a bug in JMockit; I will look into that. However, if you want to mock objects that implement an interface and get injected by Guice, I would...

Roboguice crasshes app at launch

java,android,gradle,guice,roboguice

Ok guys, I found it on my own. I injected util class inside singleton LawCaseManager, which was injected during app creation. I searched for some injection cycles/endless loops or race conditions, but haven't found any obvious one. All in all, when I removed injection inside singleton class, everything worked like...

Guice: bind parameters that do NOT have an annotation

guice

You don't have to target those injection points requiring the A implementation - you just need to write a binding for them. Recall that every binding in Guice is represented with a Key and make sure to add one for both cases. This way any I without a binding annotation...

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

java,constructor,dependency-injection,guice

If I am understanding you correctly, you are just trying to get an instance of ExternalService to pass to your Foo class constructor. You can call injector.getInstance(ExternalService.class): class MyApplication { Injector injector = Guice.createInjector(new ExternalServiceModule()); ExternalService externalService = injector.getInstance(ExternalService.class); Bar someBar = new Bar(); Foo foo = new Foo('someName', someBar,...

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

java,playframework,guice,webjars,playframework-2.4

This was a problem in sbt-web. They've increased the limit: https://github.com/sbt/sbt-web/issues/104

Configuring a Provider that returns a generic type in Guice

java,dependency-injection,guice,jdbi

Thanks to @condit for pointing me at something that enabled me to solve the issue. It's actually very simple. I changed the Provider implementation to use field injection for the Handler like this: public class DAOProvider<T> implements Provider<T> { private @Inject Handle handle; private final Class<T> daoType; public DAOProvider(Class<T> daoType)...

Is guice 4.0 backwards compatible with 3.x?

guice,guice-3

I haven't any official source but from my experience there isn't any compatibility issue. I use several guice features (bindings, provider, scopes...) and some extensions (assisted injection, multibindings, custom scopes). I switched from guice 3.0 to guice 4.0-beta4 (then 4.0-beta5, 4.0) without any problem. My initial motivation was the java-8...

Guice: binding non-immediate dependencies

java,dependency-injection,guice

The other bindings and injections you need should be set up just like the first one. Use @Inject wherever the instance is needed, and bind the interface to an impl in your module. I've added 4 lines below (annotated 2 injection sites and defined 2 more bindings): public interface MyService...

How to get a list of objects from Guice by their classes?

java,guice

You can use multibindings for this: Multibinder<AbstractTransformer> multibinder = Multibinder.newSetBinder(binder(), AbstractTransformer.class); multibinder.addBinding().to(FirstTransformer.class); multibinder.addBinding().to(SecondTransformer.class); multibinder.addBinding().to(ThirdsTransformer.class); Then you can inject Set<AbstractTransformer>: @Inject CombinedTransformer(Set<AbstractTransformer> transformers) { // do whatever you want with the set } But you can't do it without using multibindings directly. If...

How to bind two classes into one classes using google guice?

java,selenium-webdriver,guice

It is not entirely clear to me what problem you are trying to solve. If you have class B and want to use the methods of two different classes (A and C) in class B, then it looks like you just need to declare the dependency of class B on...

my Google Guice method interceptor doesn't execute but Why?

java,dependency-injection,guice

I am answering after finding the real reason. Its so simple that its really tricky. Method interception only works if you bind the interface with the class and not an instance of this implementation. so instead of 'bind(MockCalledService.class).toInstance(new MockCalledServiceImpl());' we should write 'bind(MockCalledService.class).toInstance(MockCalledServiceImpl.class);' Seems instances are not proxied :(...

How can I make a non-assisted dependency assisted?

java,guice,third-party-api,assisted-inject

First of all, it is rare that you want to be passing instances of MyObject around in your class for exactly the reasons you describe. You have no control over them, so you can't add @Assisted annotations, you can't add method interceptors, etc. etc. Plus, what happens when you want...

Guice: Using providers to get multiple instances:

java,dependency-injection,guice

This happens because you just call toString without putting the resulting string anywhere (eg the call to System.out.println) However providers are not intended to be used like that. You should not call Provider.get yourself: instead require the result of the provider, register your provider and let Guice do its job...

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

java,lambda,java-8,guice,guice-3

This unreadeable exception happens when you have a bad configuration in one yours guice modules and you are using java 8 lambdas and guice 3. I have deal a lot of time with this issue. Each time, i solved the problem by upgrading to guice 4 beta. One of its...

MyBatis multiple data sources using single mapper

java,guice,mybatis

You need to bind your MyBatisModule privately and expose the mappings with a unique binding attribute. I've got an example below. I've verified that it works, too :) DaoModule: This module is setup to bind a single mapper to a key with a specific data-source. Note that this class is...

Guice dynamic inject with custom annotation

java,inversion-of-control,guice,inject

I work out follow CustomInjections Code like this public class PropsModule extends AbstractModule { private final Props props; private final InProps inProps; private PropsModule(Props props) { this.props = props; this.inProps = InProps.in(props); } public static PropsModule of(Props props) { return new PropsModule(props); } @Override protected void configure() { bindListener(Matchers.any(), new...

Guice injection with Builder pattern for client lib

java,dependency-injection,guice,builder-pattern

It's not clear entirely what you're trying to accomplish with your injections. You may be confusing the matter further by making it about builders and other aspects of your design. I suggest you strip your code down to a SSCCE that functions but does not include any injection, and then...

Using Guice with embedded Tomcat?

tomcat,guice,spring-jdbc,jersey-2.0,hk2

Since tomcat starts in a different process, guice injector created in Jersey App is not accessible in StartApp. Guice injector have to be created in StartApp to get JdbcTemplate instamnce JdbcTemplate jdbcTemplate = Guice.createInjector(new PaymentGatewayModule()).getInstance(JdbcTemplate.class); ...

Guice and restricting clients to getting only certain instances

java,guice,hexagonal-architecture

Ah, PrivateModule is one answer. One PrivateModule at the app level which exposes only the Admin interface: public class PrivateModuleTest { public static interface Admin {} public static class AdminImpl implements Admin { @Inject public AdminImpl(BusLogic x) {} } public static interface BusLogic {} public static class BusLogicImpl implements BusLogic...

Why Guice prevents from binding to Provider?

java,dependency-injection,guice

I guess it is because Provider interface is very special to Guice. In fact, all its internal machinery is implemented in term of providers. Moreover, this could create ambiguities. If bindings to providers were possible: bind(SomeClass.class).to(SomeClassImpl1.class); bind(new TypeLiteral<Provider<SomeClass>>() {}).to(() -> new SomeClassImpl2()); then what should Guice inject here? @Inject OtherClass(Provider<SomeClass>...

Guice Singleton Static Injection Pattern

java,dependency-injection,guice

You're thinking about dependency injection incorrectly. Dependency Injection and Service Locator are mirror-images of each other: with a service locator, you ask it for an object. With dependency injection, you don't go looking for dependencies, they're just handed to you. Basically, "it's turtles all the way down"! Every dependency your...

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

java,collections,guava,guice

The easiest way is to loop across the values: for (ObjectType type : ObjectType.values()) { // Assumes you've created a binding annotation @YourAnnotation(ObjectType) along // with an implementation called YourAnnotationImpl. bind(Boolean.class) .annotatedWith(new YourAnnotationImpl(type)) .toInstance(Boolean.TRUE)); // Now you can inject "@YourAnnotation(Type1) Boolean yourValue" and so on. } However, though it may...

Is there an equivalent of Guice Providers in Simple Injector?

java,c#,dependency-injection,guice,simple-injector

I found the following example in the SimpleInjector docs http://simpleinjector.readthedocs.org/en/latest/howto.html#register-factory-delegates public static void AllowResolvingFuncFactories(this ContainerOptions options) { options.Container.ResolveUnregisteredType += (s, e) => { var type = e.UnregisteredServiceType; if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Func<>)) { return; } Type serviceType = type.GetGenericArguments().First(); InstanceProducer registration =...

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

java,dependency-injection,guice

A feature specifically matching "mixing injection and parameters passed" would be Assisted Injection. class C { // Guice will automatically create an implementation of this interface. // This can be defined anywhere, but I like putting it in the class itself. interface Factory { C create(ConfigurationField passedIn); } @Inject private...

Empty Multibinder/MapBinder in Guice

java,plugins,dependency-injection,guice

In the documentation for MapBinder, it says: Contributing mapbindings from different modules is supported. For example, it is okay to have both CandyModule and ChipsModule both create their own MapBinder, and to each contribute bindings to the snacks map. When that map is injected, it will contain entries from both...

Switching among Spring, Guice, Weld or other DI implementations

spring,dependency-injection,guice,weld,jsr330

If you strictly stick to JSR330 features, it is possible to provide a framework jar that can be used by all three implementing DI-frameworks you mentioned. To allow CDI to scan the module, you should provide a bean.xml, but I wouldn't call that code invasive. If you need to provide...

Get implementations off a MapBinder in Guice

java,guice

You aren't causing your EntryPoint to be injected anywhere. You want to do EntryPoint ep = injector.getInstance(EntryPoint.class); or if that won't work, injector.injectMembers(this); from within EntryPoint....

Google Guice bind by annotation and/or package

java,dependency-injection,guice

I would do something like this: @Override protected void configure() { try { for (ClassInfo classInfo: ClassPath.from(getClass().getClassLoader()).getTopLevelClasses("my.package.name")) { bind(classInfo.load()).asEagerSingleton(); } } catch (IOException e) { // Do something } } ClassPath is coming from the Guava library which Guice 4 depends. If you're using Guice 3 you will probably need...

Inject Guice on a static final property?

guice

It is possible to get Guice to inject into static fields. See Static Injections in the Guice documentation. But I'm not sure about static final. final fields also carry the guarantee that they are initialized exactly once (unless reflection is used). Guice may be able to work around this by...

Is there a way I can make null variables automatically fail fast in my code base unless they're marked with `@Nullable`?

java,nullpointerexception,guice,nullable

It is automated, not done with sheer discipline. As Louis Wasserman noted, Google's testing code has special treatment for parameters that are marked as @Nullable. It can be good to fail fast during testing or at run time, but it's even better to learn about problems at compile time or...

Guice : Inject an ArrayList of Strings

java,arraylist,guice,inject

I think you are misunderstanding how modules are supposed to work. Modules don't create the objects, modules define rules for how objects might be created when they are needed. The reason MapBinder would help is that you would define all of the services in your radio buttons list, and then...

bootstrapping guice injector

java,guice

In general, yes: Inject a Provider to get your objects later, and don't hold on to your Injector directly any longer than necessary. Ideally, your bootstrap should be just that: It should instantiate your Injector and get some sort of whole-application instance. This is particularly important because Guice is helpful...

Guice-servlet unit testing

java,unit-testing,servlets,guice,guice-servlet

In order to unit test your servlet (instance of HttpServlet), you do not need any framework - you can just create new instance of the servlet class, and directly call desired method while passing mocked request and response objects. If you need to isolate your code from Guice dependencies, you...

Guice inject based on annotation value

java,annotations,guice,inject

If you know that @AutoConfig(provider = JsonConfigProvider) ConfigLoader<?> jsonConfig is going to return you exactly the results of jsonConfigProvider.get(), and JsonConfigProvider obviously has a public parameterless constructor for newInstance to work, why wouldn't you just ask for a JsonConfigProvider in the first place? Fundamentally Guice is just a Map<Key, Provider>...

Guice: Configure singleton without @Singleton or otherwise modifying implementation

java,binding,singleton,guice

See: https://github.com/google/guice/wiki/Scopes Scopes Guice uses annotations to identify scopes. Specify the scope for a type by applying the scope annotation to the implementation class. Scopes can also be configured in bind statements: bind(Service.class).to(ServiceImpl.class).in(Singleton.class); should work for you....

Got “failure in processEncodedAnnotation” when mixing guice and scala on Android

java,android,scala,annotations,guice

You have to run sbt clean before running sbt android:run. If you're not using sbt then you may have to clean your project before rebuilding it. For more information, see here....

Injecting 3rd Party libraries w/ Guice @Provides

dependency-injection,guice,roboguice

That seems to be about right, but you don't need the bind statements: that tells Guice to construct instances itself using a no-arg public constructor, which it can't find. Your @Provides ThirdPartySingleton1 tells Guice everything it needs to know. You still need a configure method, because it's abstract, but you...

Spring vs Guice instantiating objects

java,spring,dependency-injection,guice

1 - Does this mean that all objects created with Spring ApplicationContext are Singletons ? No. But Spring's default scope is singleton. If you want a different scope, you must explicitly declare it in the bean configuration. In Java configuration, you do that with the @Scope annotation. With XML...

If I use Mockito do I even need Guice?

unit-testing,dependency-injection,mocking,mockito,guice

Guice and Mockito have very different and complementary roles, and I'd argue that they work best together. Consider this contrived example class: public class CarController { private final Tires tires = new Tires(); private final Wheels wheels = new Wheels(tires); private final Engine engine = new Engine(wheels); private Logger engineLogger;...

Guice: @Provider vs toProvider binding [duplicate]

java,dependency-injection,guice

When you use @Provides, you write one method in your module. When you use toProvider, you actually create an entire class, which has all the complexity of making a class, as opposed to a single method. Ultimately, both work, and both allow you to pass in injected dependencies. Just choose...

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

java,playframework,playframework-2.0,guice,guice-3

A found a workaround. I just used an access method provided by Play framework 2.4 since it fully integrates Guice. Here is my Authentication Wrapper class: public class AuthenticatorWrapper extends Security.Authenticator { private final Security.Authenticator authenticator; public AuthenticatorWrapper() { authenticator = Play.application().injector().instanceOf(Security.Authenticator.class); } @Override public String getUsername(Http.Context ctx) { return...

Can Guice instantiate my classes from class literals?

java,guice

You could do something very simple like this: class Module extends AbstractModule { Properties properties; Module(Properties properties) { this.properties = properties; } @Override protected void configure() { for (Entry<Object, Object> entry: properties.entrySet()) { try { Class<?> abstractClass = Class.forName((String)entry.getKey()); Class implementation = Class.forName((String)entry.getValue()); bind(abstractClass).to(implementation); } catch (ClassNotFoundException e) { //Handle...

Having Spring's IoC container instantiate beans with zero config (like Google Guice's behaviour)

java,spring,guice,spring-ioc

My question is: is there a way to make Spring manage any class I ask the ApplicationContext to instantiate without me having to register them in an Annotated Config (or XML config)? No, it's not possible. This is simply not how Spring is designed. You must either implicitly (e.g....

Using Generics and Reflections in Java for interface method implementation

java,generics,reflection,guice

Your code doesn't make much sense I guess, what one will pass is the Class instance, thus to use for reflection, you can't call any method on it. You can perhaps do some reflection. A better attempt would be: public synchronized void doService(<? extends MyListener> listenerObj) { //... //... //......

In guice is there a difference between @provides and bind()?

java,dependency-injection,guice

If you do bind(MyInterface.class).to(MyImplementation.class) Guice creates the instance for you. This enables certiain things like AOP. If you do @Provides MyInterface provideMyInterface() { return new MyImplementation(); } then Guice didn't create the instance so AOP won't work. Also, it requires an accessible constructor for MyImplementation. Generally, this form is only...

Inject values of a Map with Guice

java,dependency-injection,guice

Just use a MapBinder, e.g. protected void configure() { MapBinder<String, IService> mapBinder = MapBinder.newMapBinder(binder(), String.class, IService.class); mapBinder.addBinding("keyA").to(IServiceA.class); mapBinder.addBinding("keyB").to(IserviceB.class); } Then you inject the entire map, e.g. public class IServiceController { @Inject private Map<String, IService> mapping; } ...

JPA Entity not registered with EntityManager

java,hibernate,jpa,guice

After talking to a friend who implemented a project using the same architecture and similar technology I came to find out that the cause is due to a JPA Hibernate limitation. Unlike many other annotations, the annotations of the JPA implementation can only be detected on the project that implement...

Guice Provider vs EntityManager

java,jpa,guice,guice-servlet,guice-persist

You need Provider<EntityManager> because Guice's built-in persistence and servlet extensions expect EntityManager to be request-scoped. By injecting a request-scoped EntityManager from a service held in a singleton servlet, you're making a scope-widening injection, and Guice won't store data from a stale, mismatched EntityManager. Providers Provider is a one-method interface that...

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

java,guice,dropwizard

Guice will override bindings when you specify them as a class annotation. Documentation: If there's conflicting scopes on a type and in a bind() statement, the bind() statement's scope will be used. If a type is annotated with a scope that you don't want, bind it to Scopes.NO_SCOPE. You can...

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

properties,guice

Thanks to durron597 for the pointer to the related question which gave me enough to figure out. The answer is to use a child injector to take action on the previous injectors output. Example below: Injector propInjector = Guice.createInjector(new PropertiesModule()); PropertiesService propService = propInjector.getInstance(PropertiesService.class); Injector injector = propInjector.createChildInjector(new MyModule(Objects.firstNonNull(propService.getProperties(), new...

Java - How to log metrics from a ThreadPool?

java,logging,threadpool,guice

I share @chubbsondubs opinion, that there must be a synchronization issue elsewhere in the code. My suggestions to prove some things were: Try logging getTaskCountand getCompletedTaskCount. This led to your observation, that there is indeed only 1 Task in the queue at one given time. Instead of composition, extend ThreadPoolExecutor...

Proper Scopehandling in GUICE @Singleton vs. Default Scope

java,scope,singleton,guice

Although singletons save object creation (and later garbage collection), initialization of the singleton requires synchronization; ... Now, what exactly does "initialization of the singleton" mean in this context? Is initialization done once? Everytime it is injected? Here is the implementation of the singleton scope (it is slightly different in...

Injections in guice don't work everywhere [duplicate]

java,guice

If you do not create your instances with .getInstance() nothing will be injected. The annotation is not magic. You have to use requestStaticInjection() on static references that are annotated with @Inject. This is all explained in extreme detail in the Guice documentation....

How to annotate injector.getInstance?

java,junit,dependency-injection,guice

Use Injector.getInstance(Key): injector.getInstance(Key.get(RoutingResponseRepository.class, firstType.class)) When referring to a binding, Guice internally uses an immutable Key instance, which refers to an annotation status (a binding annotation class, a binding annotation instance, or no binding annotation) combined with a type (a class literal, a Type instance, or a TypeLiteral). Matching this matrix,...

How to bind named providers in a Jukito module?

gwt,junit,mockito,guice,gwtp

I assume LoginWidgetPresenter has a bare CurrentUserDto injected. The parameter to your test method doesn't change the dependencies of the LoginWidgetPresenter. To handle this, you could have two different modules, each binding CurrentUserDto to a different Provider.

How inject generic interface implementation with guice

java,generics,dependency-injection,guice

You haven't defined a binding for C.class with the given annotation. The only annotated binding you've defined is for A.class. I can't say for sure what precisely is wrong since other parts of your code don't make entire sense (a SSCCE as always would be instrumental in helping us help...

Is it possible to inject value to modules

java,dependency-injection,guice

Though it is possible to inject into a Module, or to get a Module from an Injector, it's a much better design decision not to: Modules can access their own injectors in limited ways, so having @Inject methods and fields on a Module introduces a second Injector and that could...

Guice - “dynamic” binding?

java,dependency-injection,scope,guice

Why not write your own factory? public class SystemOutPrinterFactory { private final String prefix; public SystemOutPrinterFactory(@Named("prefix") String prefix) { this.prefix = prefix; } public SystemOutPrinter createWithSuffix(String suffix) { return new SystemOutPrinter(prefix, suffix); } } The SystemOutPrinter class is public and non-abstract with a public constructor, so this should work. The...

how to auto-wire HibernateBundle with guice on dropwizard?

java,hibernate,guice,dropwizard

Here is how I end up doing. I never got an answer from here or mailing list so I would consider this hackish and probably not the proper way to do it but it works for me. In my module (that extends abstractmodule) : private final HibernateBundle<MyConfiguration> hibernateBundle = new...

Guice: injecting factory-generated instances properly

java,groovy,dependency-injection,guice

The whole problem begins here in WidgetServicePerfTesterModule class, in the following block of code: @Provides public WidgetGenerator provideSimpleWidgetGenerator() { new SimpleWidgetGenerator(50) } An instance of SimpleWidgetGenerator is created using this constructor: SimpleWidgetGenerator(int numWidgets) { super() this.numWidgets = numWidgets } and since this object is created manually injecting WidgetClient into SimpleWidgetGenerator...

Guice: instantiating a singleton before creating the module

java,dependency-injection,guice

Can you take the whole Optional and use bind(...).toInstance(...)? public static MyClass createMyClassObject( Optional<SpecialInterface> customSpecialInterfaceObject) { MyClassModule myClassModule = new MyClassModule(customSpecialInterfaceObject); Injector injector = Guice.createInjector(myClassModule); MyClassFactory instance = injector.getInstance(MyClassFactory.class); return instance.createMyClassObject(); } class MyClassModule extends AbstractModule { private final Optional<SpecialInterface> customObject;...

How can I construct a class when the super class uses @Inject?

java,gwt,dependency-injection,guice,gin

You need to accept an A as well: @Inject B(A a, D d) { super(a); this.d = d; } Then Guice should inject both the A and the D, and you just pass the A up to the superclass constructor. Just because a constructor is marked with @Inject doesn't mean...

Guice @Provides Methods vs Provider Classes

java,dependency-injection,guice,roboguice

As far as I know, they're exactly equivalent for most simple cases. /** * Class-style provider. * In module: bind(Foo.class).annotatedWith(Quux.class).toProvider(MyProvider.class); */ class MyProvider implements Provider<Foo> { @Inject Dep dep; // All sorts of injection work, including constructor injection. @Override public Foo get() { return dep.provisionFoo("bar", "baz"); } } /** *...

Error in binding: No implementation was bound - Guice

java,guice

In the PersistenceModule you bind the PersistenceStore without annotation. In the constructor of the FooService you ask for a dependency annotated with @Named("fooPersistence"). Either use the annotations in both the binding and the injection point or remove them. By the way: Prefere onami persist if you have the chance. It...

Using google-guice with out bind code

java,dependency-injection,guice

Yes, there is a way to use annotations to specify bindings, it is explained in the Guice docs. An example from that page: @ImplementedBy(PayPalCreditCardProcessor.class) public interface CreditCardProcessor { ChargeResult charge(String amount, CreditCard creditCard) throws UnreachableException; } @ProvidedBy(DatabaseTransactionLogProvider.class) public interface TransactionLog { void logConnectException(UnreachableException e); void logChargeResult(ChargeResult result); } @ImplementedBy and...

Modern Akka DI with Guice

java,akka,guice

Use Creator to create ActorRefs in provider methods of your guice module. To distinguish between the different ActorRefs, which are untyped, use annotations on your provider methods and injection points as you would any guice system. For example, In your guice module: @Override protected void configure() { bind(ActorSystem.class).toInstance(ActorSystem.apply()); bind(FizzService.class).toInstance(new FizzServiceImpl());...

guice injection in static variable

java,guice,guice-3

Guice does not inject static fields by design. You can request static injection but this should be done only as a crutch: This API is not recommended for general use because it suffers many of the same problems as static factories: it's clumsy to test, it makes dependencies opaque, and...

Binding a value to one of two possibilities in Guice

java,guice

Your first design seems like the best option to me if you don't need the binding to change at runtime (i.e. the binding is constant as of injector creation time). For any value you decide at runtime, you'll need a Provider or a @Provides method: public class SimpleIfBlockModule extends AbstractModule...

Jersey resource that matches any path

java,servlets,guice,jersey-1.0

@peeskillet's answer is indeed correct, in the sense that it describes how you can create a Jersey resource that matches any path. However, my goal of creating a resource that delivers 404 responses for whenever any other unmatched path is requested is not quite met by this answer: At least...

Is it considered bad practice/design to create 10s/100s of Guice Injectors?

java,design-patterns,guice

At the level of abstraction you described, that sounds like a reasonable solution, and conducive to some good design patterns (like loose coupling and instance immutability). To the best of my knowledge Guice will not pose any greater threat of memory leaks or other performance problems than any comparable solution...

Using @Assisted inject with multiple params of same Type (@Named params)

java,dependency-injection,guice,assisted-inject

Have a look at this documentation: Making parameter types distinct The types of the factory method's parameters must be distinct. To use multiple parameters of the same type, use a named @Assisted annotation to disambiguate the parameters. The names must be applied to the factory method's parameters: public interface PaymentFactory...

Does guice allow injectMembers into a constructor?

java,constructor,guice,inject

Yes, this should work. It's OK for the process of constructing one instance to cause other injections to occur (in fact, this is the way dependency injection works normally). A probably better alternative for the same effect would be: @Inject Foo(Provider<Bar> barProvider) { this.bar = barProvider.get(); } Since this will...

RoboFragment is not applicable to method FragmentTransaction.add(int,Fragment)

java,android,android-fragments,guice,roboguice

From what I can see, RoboFragmentActivity extends android.support.v4.app.FragmentActivity from the support libraries. I think you should call getSupportFragmentManager() instead of getFragmentManager()....

How to use Guice AssistedInject with multiple implementations of an interface?

java,guice,factory,assisted-inject

FactoryModuleBuilder isn't as powerful as you think it is—it has no provision to switch between implementations, and is only used for mixing injected dependencies with other constructor arguments. Luckily, Guice makes your factory easy to write. What it sounds like you're looking for is an implementation of this interface: public...

How to get a extended SubClass from Google Gin using GinFactoryModuleBuilder?

java,gwt,dependency-injection,guice,gin

You can just remove everything from the configure method and keep only the following : install(new GinFactoryModuleBuilder() .implement(Animal.class, Rooster.class) .build(AnimalFactory.class)); and then use the factory as you did to get instance of Rooster from the factory. Or, you can change your factory method to return Rooster & change configure as...

Create and initialize a singleton with Guice [duplicate]

java,guice

You can use the provider interface public class StorageProxyProvider implements Provider<StorageProxy> { public StorageProxy get() { StorageProxy storageProxy = new StorageProxy(); storageProxy.init(); return storageProxy; } } public class StorageProxyModule extends AbstractModule { protected void configure() { bind(StorageProxy.class).toProvider(StorageProxyProvider.class).in(Singleton.class); } } A working example: public class StorageProxyProvider implements Provider<StorageProxy> { public StorageProxy...

Guice constructor injection of String dependency (or other unbound primitive)?

java,constructor,dependency-injection,guice

By default Guice will instantiate any object that has either An @Inject-marked non-private constructor A non-private no-args constructor A default constructor (no constructor) Because String has a no-args public constructor, new String() will create a string equivalent to "" This is deterministic behavior, and will happen with any type that...

Injecting an implementation of a generic interface subtype using Guice

java,generics,dependency-injection,guice

Conceptually, the problem is here: @Inject public ExecutorImpl(final Input<I> input, final Transformer<O, I> transformer, final Output<O> output) { When guice attempts to fulfill the dependency for, say, Input<I>, it doesn't know what type it is; that's what "It is not fully specified" means. You can fix this by specifying what...

Guice assisted inject overuse alternatives, dependency injection vs non-DI constructors

java,oop,dependency-injection,guice

You nailed down some great reasons to use assisted injection in your question: It ensures that the object instances only ever exist in a fully-initialized state, keeps your dependencies together, and frees the object's public interface from requiring a predictable parameter in every method. I don't really have any alternatives...

how to get class name of class that injects something

java,logging,guice

There isn't a nice way to do this in Guice 3. Guice 4 (in beta right now) has ProvisionListener which makes this possible, though still difficult. I wrote a library for it called Sangria.

Mockito and Guice : mocking a @Provides method

dependency-injection,mockito,guice,vertx.io

I assume that you have a class that provides some functionality. This is the class you want to unit test. It requires a tokenClient that you inject into the class to work properly. So the question you are facing is: how does my class under test get a mocked tockenClient...

Play Framework: Dependecy Inject Action Builder

scala,playframework,dependency-injection,guice,guice-3

Define your action builders inside a trait with the authentication service as an abstract field. Then mix them into your controllers, into which you inject the service. For example: trait MyActionBuilders { // the abstract dependency def authService: AuthenticationService def AuthenticatedAction = new ActionBuilder[AuthenticatedRequest] { override def invokeBlock[A](request: Request[A], block(AuthenticatedRequest[A])...

gae session data not updated

google-app-engine,guice

Since my question seems to be unclear, it actually was: Wy the hell are my session objects not persisted? A working solution for me was to manually change session attributes directly on the HttpSession whenever I want to persist changes in my session objects: updateSession(HttpServletRequest request) { HttpSession s =...

Difference between @inject and @mock annotations

gwt,junit,mockito,guice,gin

@Inject ... is an annotation which is defined in Guice and is quite simliar to Spring @Autowire. You can use these Annotations to inject a Object which you whant to use in your tests (i.e. persistence context to work with jpa) @Mock ... is an annotation to (more or less)...

How to instantiate spring managed beans at runtime?

java,spring,dependency-injection,refactoring,guice

Looks like I found a solution. As I am using java based configuration it is even simpler than you can imagine. Alternative way in xml would be lookup-method, however only from spring version 4.1.X as it supports passing arguments to the method. Here is a complete working example: public class...