Skip to content

Instantly share code, notes, and snippets.

@elucash
Created October 22, 2015 22:47
Show Gist options
  • Save elucash/aa88dcf6cfbe90aea68c to your computer and use it in GitHub Desktop.
Save elucash/aa88dcf6cfbe90aea68c to your computer and use it in GitHub Desktop.
Showcase of Immutables and Guice for typed id generation
package abc;
import com.google.inject.Injector;
import com.google.inject.Guice;
import javax.inject.Inject;
import javax.inject.Provider;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.immutables.value.Value;
import org.immutables.value.Value.Style.ImplementationVisibility;
// You can place styles on package or classes or as meta
// annotations, as described in documentation (immutables.github.io/style.html)
@Value.Style(
typeAbstract = "_*",
typeImmutable = "*",
visibility = ImplementationVisibility.PUBLIC,
defaults = @Value.Immutable(builder = false, copy = false))
public class Sample {
// There's no real need in this super-type,
// But I usually use something like that when I have
// a lot of similar IDs or wrapper types.
abstract static class BaseId<T> {
@Value.Parameter
abstract T value();
@Override
public String toString() {
return value().toString();
}
}
// using "reverse" style, StringId class will be
// generated from _StringId abstract value type
@Value.Immutable
abstract static class _StringId extends BaseId<String> {}
@Value.Immutable
abstract static class _LongId extends BaseId<Long> {}
interface IdGenerator {
long newId();
}
// First option is to use module
static class IdModule extends AbstractModule {
@Override
protected void configure() {}
@Provides
public StringId stringId(IdGenerator generator) {
return StringId.of("id_" + generator.newId());
}
@Provides
public LongId longId(IdGenerator generator) {
return LongId.of(generator.newId());
}
}
// Second option is to use provider
static class StringIdProvider implements Provider<StringId> {
@Inject
IdGenerator generator;
@Override
public StringId get() {
return StringId.of("id_" + generator.newId());
}
}
static class StringIdUser {
@Inject
StringId id;
}
static class Gen implements IdGenerator {
@Override
public long newId() {
return System.currentTimeMillis();
}
}
public static void main(String... args) {
Injector usingModule = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
install(new IdModule());
bind(IdGenerator.class).to(Gen.class);
}
});
StringIdUser user = usingModule.getInstance(StringIdUser.class);
System.out.println(user.id);
Injector usingProvider = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(IdGenerator.class).to(Gen.class);
bind(StringId.class).toProvider(StringIdProvider.class);
}
});
user = usingProvider.getInstance(StringIdUser.class);
System.out.println(user.id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment