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>...
java,android,dependency-injection,guice,roboguice
You have a lot of options, actually. Here are three: Factory object Frankly, I don't think this design needs Guice for this particular problem. Instead, create a simple interface to populate with relevant switch statements: interface DealFactory { ScoreCalculator getFromDeal(Deal deal); ScoreValidator getFromDeal(Deal deal); } You might be thinking, "But...
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...
jpa,jersey,guice,guice-3,guice-persist
There problem was that the MissionController class is managed by Jersey, and not by Guice, so it wasn't intercepted by the JpaLocalTxnInterceptor I solved it by moving DB-related code to another class, like this: class MissionController { @Inject MissionDao dao; .... } public class MissionDao { @Inject Provider<EntityManager> em; @Transactional...
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 ...
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....
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...
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...
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...
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) { //... //... //......
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.
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...
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...
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...
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...
spring,dependency-injection,guice,guice-3
Assuming I am understanding your question correctly, you would like to pick a particular concrete implementation to bind based on a particular parameter. One way to do this is to create a module that takes as a constructor the parameters you need for deciding which module to bind. The logic...
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 =...
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...
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...
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...
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...
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...
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...
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...
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;...
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 =...
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...
@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)...
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...
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...
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"); } } /** *...
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...
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...
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>...
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...
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...
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...
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...
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.
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...
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...
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()....
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...
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...
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); ...
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());...
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)...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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 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...
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...
My solution was to add a RatingId class that wraps an integer and create a factory RatingIds that I could then return static and use as parameters. I overloaded the getRatingById method in my RatingService interface to accept the new RatingId type, and then inject the rating service into my...
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...
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...
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...
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...
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...
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])...
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...
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...
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...
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....
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...
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...
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
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....
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....
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...
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...
java,class,generics,dependency-injection,guice
You can use Key to get instances of these bindings: injector.getInstance(Key.get(new TypeLiteral<Dal<RoutingResponse>>() {})); ...
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,...
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...
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...
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...
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; } ...
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...
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;...
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...
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 :(...
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...
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...
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....
Guice injector has ... array as an argument: Guice.createInjector(Module... modules); So you can simply do: Guice.createInjector(new ExchangeModule(), new RealmModule()); If there are some conflicts you can try binding annotations or untargetted bindings. EDIT: This might show how you could avoid conflicts: bind(NetworkService.class).annotatedWith(Exchange.class).to(ExchangeManager.class); bind(NetworkService.class).annotatedWith(Realm.class).to(RealmManager.class); then: @Inject @Exchange private NetworkService exchangeService; EDIT...
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...
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...
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...
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...
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,...
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...
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...