I am trying to find best practice to solve the following situation:
public class AppModule extends Module { @Override protected void configure() { install(new JpaPersistModule("myJpaUnit").addFinder(Dao.class)); bind(MyJpaInitializer.class).asEagerSingleton(); } @Provides @IndicatesSomeConstantMap @Singleton Map<String, String> getMappings(Dao dao) { ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
I need to add @IndicatesSomeConstantMap to other classes. It seems that the only way getMappings can get Tao is by binding MyJpaInitializer as an EagerSingleton that feels wrong. What is the preferred way to resolve these hierarchical dependencies?
EDIT:
Based on the answer from @jeffcrowe, I came up with something like:
public class Module1 extends PrivateModule { @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface Jpa1{} @Singleton public static class JpaInitializer1 { @Inject public JpaInitializer1(@Jpa1 PersistService service) { service.start(); } } public interface Finder1 { @Finder(query="FROM Foo", returnAs = ArrayList.class) List<Foo> getAll(); } @Override protected void configure() { install(new JpaPersistModule("firstJpaUnit").addFinder(Finder1.class)); bind(JpaInitializer1.class); } @Provides @Exposed @Jpa1 PersistService getPersistService(Provider<PersistService> provider) { return provider.get(); } @Provides @Exposed @Jpa1 Finder1 getFinder(Finder1 finder, JpaInitializer1 init) { return finder; } }
This handles the dependency, wrapping it in a provider and feeling cleaner for me than using the eagerSingleton approach. It also hides the JpaModule behind a private module, which makes it useful in situations where multiple save modules are connected. The new problem is that since the Finder is already associated with the JpaPersistModule, we must add the @ Jpa1 annotation to each injection of Finder1. Is there any way around this?
source share