Walter
Walter

Reputation: 1470

Guice Persist with multiple persistence units

I have setup guice with multiple persistence units, but the problem I have is that I'd prefer to have a default instead of having to explicitly declare one or the other. When I want the "other" one, I will explicitly ask for it. When I want the default one, I'll want to do the same thing as if I only had a single PU.

I tried merely installing the JpaPersistModule inside a PrivateModule, but that didn't change anything. If I bind to the "default" annotation and attempt to rebind as well with no "annotatedWith" classifier, I get a rebinding error.

Is this possible? I believe with the equivalent in CDI, I can inject the injection point to look at it and make that determination on the spot. I have yet to find an equivalent in guice, but there must be.

In terms of code, this is what I have (but do not want):

@Inject
public SomethingService(@Primary Repository repository)

@Inject
public SomethingElseService(@Secondary Repository repository)

Instead, I want this:

@Inject
public SomethingService(Repository repository)

@Inject
public SomethingElseService(@Secondary Repository repository)

Upvotes: 0

Views: 244

Answers (1)

Joe
Joe

Reputation: 607

This is very similar to what I've been trying to do with @Named annotations instead of @Primary / @Secondary annotations in How to bind a dynamic @Named binding

I've gotten it to work with Providers and PrivateModules; something along the lines of the untested following code would (I think) mirror the setup I've gotten to work, although potentially all of it may not be necessary in your case (and possibly Jeff's answer to my question would provide some more context):

public class PrimaryRepositoryModule extends AbstractModule {
    @Provides
    public Repository provideRepository() {
         return new PrimaryRepository()
    }
}

public class SecondaryRepositoryModule extends AbstractModule {
    public void configure() {
        install(new PrivateSecondaryRepositoryModule())
    }
    private static class SecondaryProvider implements Provider<Repository> {
        public Repository get() {
            return new SecondaryRepository()
        }
    }
    private static class PrivateSecondaryModule extends PrivateModule {
        public void configure() {
            bind(Repository.class).annotatedWith(Secondary.class)
                .toProvider(SecondaryProvider.class)
            expose(Repository.class).annotatedWith(Secondary.class)
    }
}

Upvotes: 0

Related Questions