Support
Quality
Security
License
Reuse
kandi has reviewed guice and discovered the below as its top functions. This is intended to give you an instant insight into guice implemented functionality, and help decide if they suit your requirements.
Latest release: [5.1.0](https://github.com/google/guice/wiki/Guice510)
Documentation: [User Guide](https://github.com/google/guice/wiki/Motivation), [Latest javadocs](https://google.github.io/guice/api-docs/latest/javadoc/index.html) [5.1.0 javadocs](https://google.github.io/guice/api-docs/5.1.0/javadoc/index.html)
Continuous Integration: [](https://github.com/google/guice/actions)
Mailing Lists: [User Mailing List](http://groups.google.com/group/google-guice) <br/>
License: [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0)
Create MessageDigest with Guice
final MessageDigestModule extends AbstractModule {
@Provide
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("MD5");
}
}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Md5 {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Sha256 {}
final MessageDigestModule extends AbstractModule {
@Provide
@Md5
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("MD5");
}
@Provide
@Sha256
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("SHA-256");
}
}
@Inject
@Sha256
Supplier<MessageDigest> sha128DigestSupplier;
-----------------------
final MessageDigestModule extends AbstractModule {
@Provide
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("MD5");
}
}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Md5 {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Sha256 {}
final MessageDigestModule extends AbstractModule {
@Provide
@Md5
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("MD5");
}
@Provide
@Sha256
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("SHA-256");
}
}
@Inject
@Sha256
Supplier<MessageDigest> sha128DigestSupplier;
-----------------------
final MessageDigestModule extends AbstractModule {
@Provide
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("MD5");
}
}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Md5 {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Sha256 {}
final MessageDigestModule extends AbstractModule {
@Provide
@Md5
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("MD5");
}
@Provide
@Sha256
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("SHA-256");
}
}
@Inject
@Sha256
Supplier<MessageDigest> sha128DigestSupplier;
-----------------------
final MessageDigestModule extends AbstractModule {
@Provide
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("MD5");
}
}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Md5 {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Sha256 {}
final MessageDigestModule extends AbstractModule {
@Provide
@Md5
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("MD5");
}
@Provide
@Sha256
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("SHA-256");
}
}
@Inject
@Sha256
Supplier<MessageDigest> sha128DigestSupplier;
-----------------------
@Provides
MessageDigest provideMD5() throws NoSuchAlgorithmException {
return MessageDigest.getInstance("MD5");
}
@Inject
Provider<MessageDigest> md5Provider;
...
// Later in the class
MessageDigest md5 = md5Provider.get();
-----------------------
@Provides
MessageDigest provideMD5() throws NoSuchAlgorithmException {
return MessageDigest.getInstance("MD5");
}
@Inject
Provider<MessageDigest> md5Provider;
...
// Later in the class
MessageDigest md5 = md5Provider.get();
Spring Boot Logging to a File
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.ConsoleHandler.formatter = org.springframework.boot.logging.java.SimpleFormatter
-----------------------
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.ConsoleHandler.formatter = org.springframework.boot.logging.java.SimpleFormatter
Java : io.protostuff.compiler.parser.ParserException: Can not load proto
/some/directory/imports$ tree -d -L 2
.
├── envoyproxy
│ └── protoc-gen-validate
└── google
├── api
├── protobuf
└── rpc
import com.google.inject.Guice;
import com.google.inject.Injector;
import io.protostuff.compiler.ParserModule;
import io.protostuff.compiler.model.Message;
import io.protostuff.compiler.model.Proto;
import io.protostuff.compiler.parser.FileReader;
import io.protostuff.compiler.parser.FileReaderFactory;
import io.protostuff.compiler.parser.Importer;
import io.protostuff.compiler.parser.ProtoContext;
import java.nio.file.Path;
import java.util.List;
public final class Program {
public static void main(final String[] args) {
final Injector injector = Guice.createInjector(new ParserModule());
final FileReaderFactory fileReaderFactory = injector.getInstance(FileReaderFactory.class);
final List<Path> includePaths = List.of(
Path.of("/some/directory/imports")
);
final FileReader fileReader = fileReaderFactory.create(includePaths);
final Importer importer = injector.getInstance(Importer.class);
final ProtoContext protoContext = importer.importFile(
fileReader,
"/some/other/directory/test.proto"
);
final Proto proto = protoContext.getProto();
final List<Message> messages = proto.getMessages();
System.out.println(String.format("Messages: %s", messages));
}
}
Messages: [Message{name=SendRequest, fullyQualifiedName=.grpc.SendRequest, fields=[Field{name=data, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=document, typeName=bytes, tag=2, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}, Message{name=SendResponse, fullyQualifiedName=.grpc.SendResponse, fields=[Field{name=Status, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=Message, typeName=string, tag=2, options=DynamicMessage{fields={}}}, Field{name=DocumentList, modifier=repeated, typeName=string, tag=3, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}]
-----------------------
/some/directory/imports$ tree -d -L 2
.
├── envoyproxy
│ └── protoc-gen-validate
└── google
├── api
├── protobuf
└── rpc
import com.google.inject.Guice;
import com.google.inject.Injector;
import io.protostuff.compiler.ParserModule;
import io.protostuff.compiler.model.Message;
import io.protostuff.compiler.model.Proto;
import io.protostuff.compiler.parser.FileReader;
import io.protostuff.compiler.parser.FileReaderFactory;
import io.protostuff.compiler.parser.Importer;
import io.protostuff.compiler.parser.ProtoContext;
import java.nio.file.Path;
import java.util.List;
public final class Program {
public static void main(final String[] args) {
final Injector injector = Guice.createInjector(new ParserModule());
final FileReaderFactory fileReaderFactory = injector.getInstance(FileReaderFactory.class);
final List<Path> includePaths = List.of(
Path.of("/some/directory/imports")
);
final FileReader fileReader = fileReaderFactory.create(includePaths);
final Importer importer = injector.getInstance(Importer.class);
final ProtoContext protoContext = importer.importFile(
fileReader,
"/some/other/directory/test.proto"
);
final Proto proto = protoContext.getProto();
final List<Message> messages = proto.getMessages();
System.out.println(String.format("Messages: %s", messages));
}
}
Messages: [Message{name=SendRequest, fullyQualifiedName=.grpc.SendRequest, fields=[Field{name=data, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=document, typeName=bytes, tag=2, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}, Message{name=SendResponse, fullyQualifiedName=.grpc.SendResponse, fields=[Field{name=Status, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=Message, typeName=string, tag=2, options=DynamicMessage{fields={}}}, Field{name=DocumentList, modifier=repeated, typeName=string, tag=3, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}]
-----------------------
/some/directory/imports$ tree -d -L 2
.
├── envoyproxy
│ └── protoc-gen-validate
└── google
├── api
├── protobuf
└── rpc
import com.google.inject.Guice;
import com.google.inject.Injector;
import io.protostuff.compiler.ParserModule;
import io.protostuff.compiler.model.Message;
import io.protostuff.compiler.model.Proto;
import io.protostuff.compiler.parser.FileReader;
import io.protostuff.compiler.parser.FileReaderFactory;
import io.protostuff.compiler.parser.Importer;
import io.protostuff.compiler.parser.ProtoContext;
import java.nio.file.Path;
import java.util.List;
public final class Program {
public static void main(final String[] args) {
final Injector injector = Guice.createInjector(new ParserModule());
final FileReaderFactory fileReaderFactory = injector.getInstance(FileReaderFactory.class);
final List<Path> includePaths = List.of(
Path.of("/some/directory/imports")
);
final FileReader fileReader = fileReaderFactory.create(includePaths);
final Importer importer = injector.getInstance(Importer.class);
final ProtoContext protoContext = importer.importFile(
fileReader,
"/some/other/directory/test.proto"
);
final Proto proto = protoContext.getProto();
final List<Message> messages = proto.getMessages();
System.out.println(String.format("Messages: %s", messages));
}
}
Messages: [Message{name=SendRequest, fullyQualifiedName=.grpc.SendRequest, fields=[Field{name=data, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=document, typeName=bytes, tag=2, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}, Message{name=SendResponse, fullyQualifiedName=.grpc.SendResponse, fields=[Field{name=Status, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=Message, typeName=string, tag=2, options=DynamicMessage{fields={}}}, Field{name=DocumentList, modifier=repeated, typeName=string, tag=3, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}]
AroundInvoke: Curious name?
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception { ... }
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception {
log.info("We're about to do the thing!");
Object result = ctx.proceed();
log.info("We did the thing!");
return result;
}
-----------------------
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception { ... }
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception {
log.info("We're about to do the thing!");
Object result = ctx.proceed();
log.info("We did the thing!");
return result;
}
Guice generic type injection
public class Base<T extends Stoppable> {
protected final Injector injector;
protected T stoppable;
public Base(Class<T> type, Module... module) {
injector = Guice.createInjector(module);
var key = Key.get(com.google.inject.util.Types.setOf(type));
stoppable = injector.getInstance(key);
}
}
How to Manage JNDI Context In JUnit Tests?
private static Context context;
private static final String NAV_DS = "java:comp/env/jdbc/NavDS";
//using a provider method here so we can inject the context into the test
@Provides
public Context getContext() throws NamingException
{
if( context == null)
{
context = new InitialContext();
context.createSubcontext("java:comp/env");
context.createSubcontext("java:comp/env/jdbc");
}
return context;
}
@Provides
@Singleton
public DataSource getNavDS() throws NamingException {
BasicDataSource ds = null;
ds = new BasicDataSource();
ds.setUrl("jdbc:h2:mem:myDB;create=true;MODE=MSSQLServer;DATABASE_TO_UPPER=FALSE;");
Context context = getContext();
context.rebind(NAV_DS, ds);
return ds;
}
public class TestContextFactory implements InitialContextFactory {
private static final ThreadLocal<Context> currentContext = new ThreadLocal<Context>();
@Override
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
return currentContext.get();
}
public static void setCurrentContext(Context context) {
currentContext.set(context);
}
public static void clearCurrentContext() {
currentContext.remove();
}
}
public class MockInitialContextRule implements TestRule {
private final Context context;
public MockInitialContextRule(Context context) {
this.context = context;
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestContextFactory.class.getName());
TestContextFactory.setCurrentContext(context);
try {
base.evaluate();
} finally {
System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
TestContextFactory.clearCurrentContext();
}
}
};
}
}
@Inject
private Context context;
@Rule
public MockInitialContextRule mockInitialContextRule = new MockInitialContextRule(context);
@Test
public void testFoo()
{
Object foo = context.lookup("jdbc/NavDS");
assertNotNull(foo);
}
-----------------------
private static Context context;
private static final String NAV_DS = "java:comp/env/jdbc/NavDS";
//using a provider method here so we can inject the context into the test
@Provides
public Context getContext() throws NamingException
{
if( context == null)
{
context = new InitialContext();
context.createSubcontext("java:comp/env");
context.createSubcontext("java:comp/env/jdbc");
}
return context;
}
@Provides
@Singleton
public DataSource getNavDS() throws NamingException {
BasicDataSource ds = null;
ds = new BasicDataSource();
ds.setUrl("jdbc:h2:mem:myDB;create=true;MODE=MSSQLServer;DATABASE_TO_UPPER=FALSE;");
Context context = getContext();
context.rebind(NAV_DS, ds);
return ds;
}
public class TestContextFactory implements InitialContextFactory {
private static final ThreadLocal<Context> currentContext = new ThreadLocal<Context>();
@Override
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
return currentContext.get();
}
public static void setCurrentContext(Context context) {
currentContext.set(context);
}
public static void clearCurrentContext() {
currentContext.remove();
}
}
public class MockInitialContextRule implements TestRule {
private final Context context;
public MockInitialContextRule(Context context) {
this.context = context;
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestContextFactory.class.getName());
TestContextFactory.setCurrentContext(context);
try {
base.evaluate();
} finally {
System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
TestContextFactory.clearCurrentContext();
}
}
};
}
}
@Inject
private Context context;
@Rule
public MockInitialContextRule mockInitialContextRule = new MockInitialContextRule(context);
@Test
public void testFoo()
{
Object foo = context.lookup("jdbc/NavDS");
assertNotNull(foo);
}
-----------------------
private static Context context;
private static final String NAV_DS = "java:comp/env/jdbc/NavDS";
//using a provider method here so we can inject the context into the test
@Provides
public Context getContext() throws NamingException
{
if( context == null)
{
context = new InitialContext();
context.createSubcontext("java:comp/env");
context.createSubcontext("java:comp/env/jdbc");
}
return context;
}
@Provides
@Singleton
public DataSource getNavDS() throws NamingException {
BasicDataSource ds = null;
ds = new BasicDataSource();
ds.setUrl("jdbc:h2:mem:myDB;create=true;MODE=MSSQLServer;DATABASE_TO_UPPER=FALSE;");
Context context = getContext();
context.rebind(NAV_DS, ds);
return ds;
}
public class TestContextFactory implements InitialContextFactory {
private static final ThreadLocal<Context> currentContext = new ThreadLocal<Context>();
@Override
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
return currentContext.get();
}
public static void setCurrentContext(Context context) {
currentContext.set(context);
}
public static void clearCurrentContext() {
currentContext.remove();
}
}
public class MockInitialContextRule implements TestRule {
private final Context context;
public MockInitialContextRule(Context context) {
this.context = context;
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestContextFactory.class.getName());
TestContextFactory.setCurrentContext(context);
try {
base.evaluate();
} finally {
System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
TestContextFactory.clearCurrentContext();
}
}
};
}
}
@Inject
private Context context;
@Rule
public MockInitialContextRule mockInitialContextRule = new MockInitialContextRule(context);
@Test
public void testFoo()
{
Object foo = context.lookup("jdbc/NavDS");
assertNotNull(foo);
}
-----------------------
private static Context context;
private static final String NAV_DS = "java:comp/env/jdbc/NavDS";
//using a provider method here so we can inject the context into the test
@Provides
public Context getContext() throws NamingException
{
if( context == null)
{
context = new InitialContext();
context.createSubcontext("java:comp/env");
context.createSubcontext("java:comp/env/jdbc");
}
return context;
}
@Provides
@Singleton
public DataSource getNavDS() throws NamingException {
BasicDataSource ds = null;
ds = new BasicDataSource();
ds.setUrl("jdbc:h2:mem:myDB;create=true;MODE=MSSQLServer;DATABASE_TO_UPPER=FALSE;");
Context context = getContext();
context.rebind(NAV_DS, ds);
return ds;
}
public class TestContextFactory implements InitialContextFactory {
private static final ThreadLocal<Context> currentContext = new ThreadLocal<Context>();
@Override
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
return currentContext.get();
}
public static void setCurrentContext(Context context) {
currentContext.set(context);
}
public static void clearCurrentContext() {
currentContext.remove();
}
}
public class MockInitialContextRule implements TestRule {
private final Context context;
public MockInitialContextRule(Context context) {
this.context = context;
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestContextFactory.class.getName());
TestContextFactory.setCurrentContext(context);
try {
base.evaluate();
} finally {
System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
TestContextFactory.clearCurrentContext();
}
}
};
}
}
@Inject
private Context context;
@Rule
public MockInitialContextRule mockInitialContextRule = new MockInitialContextRule(context);
@Test
public void testFoo()
{
Object foo = context.lookup("jdbc/NavDS");
assertNotNull(foo);
}
Wire collection of objects dynamically in Guice
class ThingyModuleTest {
static class Thingy<T>{
private final T value;
Thingy(final T value) {this.value = value;}
@Override public boolean equals(final Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
final Thingy<?> thingy = (Thingy<?>) o; return Objects.equals(value, thingy.value); }
@Override public int hashCode() { return Objects.hash(value); }
}
@Singleton
static class ThingyService{
final Set<Thingy<?>> thingies;
@SuppressWarnings({"unchecked", "rawtypes"}) @Inject
ThingyService(Set<Thingy> thingies) {
this.thingies = ImmutableSet.copyOf((Set)thingies);
}
public Set<Thingy<?>> getThingies() { return thingies; }
}
abstract static class ThingyModule extends AbstractModule {
private final Set<Class<?>> classesToScan;
public ThingyModule(Class<?>... classes) {
this.classesToScan = ImmutableSet.copyOf(classes);
}
private Set<Thingy<?>> scanForThingies(){
return classesToScan.stream()
.flatMap(c-> Arrays.stream(c.getDeclaredFields()))
.filter(f->f.getType().isAssignableFrom(Thingy.class))
.filter(f-> Modifier.isStatic(f.getModifiers())&&Modifier.isFinal(f.getModifiers()))
.map(this::readThingy)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
}
@SuppressWarnings("unchecked")
private Optional<Thingy<?>> readThingy(final Field field) {
try{
field.setAccessible(true);
return Optional.ofNullable(field.get(null))
.filter(Thingy.class::isInstance)
.map(Thingy.class::cast);
} catch (IllegalAccessException e) { return Optional.empty(); }
}
@Override protected void configure() {
bind(ThingyService.class);
@SuppressWarnings("rawtypes") Multibinder<Thingy> multibinder = Multibinder.newSetBinder(binder(), Thingy.class);
scanForThingies().forEach(thingy -> multibinder.addBinding().toInstance(thingy));
}
}
static class ThingyModule1 extends ThingyModule {
public ThingyModule1() { super(Thingies1.class); }
static class Thingies1{
static final Thingy<Boolean> BooleanThingy = new Thingy<>(true);
static final Thingy<Integer> IntThingy = new Thingy<>(123);
}
}
static class ThingyModule2 extends ThingyModule {
public ThingyModule2() { super(Thingies2.class); }
static class Thingies2{
static final Thingy<String> StringThingy = new Thingy<>("hello");
static final Thingy<Long> LongThingy = new Thingy<>(123L);
}
}
@Test void validateThingyService() {
ThingyService thingyService = Guice.createInjector(new ThingyModule1(), new ThingyModule2())
.getProvider(ThingyService.class)
.get();
assertThat(thingyService).isNotNull()
.extracting(ts -> ImmutableList.copyOf(ts.getThingies()))
.asList()
.containsExactlyInAnyOrder(BooleanThingy, IntThingy, StringThingy, LongThingy);
}
}
How to add Walkmod plugin to eclipse?
<plugin>
<groupId>org.walkmod.maven.plugins</groupId>
<artifactId>walkmod-maven-plugin</artifactId>
<version>2.0.1</version>
<executions>
<execution>
<goals>
<goal>apply</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.ivy</groupId>
<artifactId>ivy</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
</plugin>
Guice load properties from System Properties
@Override protected void configure() {
Names.bindProperties(binder(), System.getProperties());
}
Runtime value injection in Dagger vs. Guice
@AssistedFactory
public interface InterfaceXFactory{
ClassX getClassX(
@Assisted("a") String a,
@Assisted("b") Integer b);
}
@AssistedInject
ClassX(
final @Assisted("a") String a,
final @Assisted("b") Integer b) {
/*...*/
}
-----------------------
@AssistedFactory
public interface InterfaceXFactory{
ClassX getClassX(
@Assisted("a") String a,
@Assisted("b") Integer b);
}
@AssistedInject
ClassX(
final @Assisted("a") String a,
final @Assisted("b") Integer b) {
/*...*/
}
QUESTION
Create MessageDigest with Guice
Asked 2022-Mar-25 at 18:00I'm trying to find a way to initialize MessageDigest with Guice. Currently I have this:
public class MyClass {
MessageDigest md;
public MyClass() {
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
....
}
I'm trying to see if it can written as:
@Inject
MessageDigest md;
But how do I make Guice call MessageDigest.getInstance("MD5")
?
ANSWER
Answered 2022-Mar-25 at 18:00Edit
I did not know MessageDigest
is a single use class. You showed an injection of that class, which by definition cannot provide multiple instances. So the question is flawed.
You must fix the problem by binding a factory function that creates an MD rather than the MD itself. E.g. a Supplier:
final MessageDigestModule extends AbstractModule {
@Provide
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("MD5");
}
}
Then when creating the injector, install new MessageDigestModule()
.
You will use @Inject Supplier<MessageDigest> md5DigestSupplier;
. At the places where you need one, you'll say md5DigestSupplier.get()
.
If you'll need more than one kind of MessageDigest
, then you should declare annotations and use them to separate the bindings.
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Md5 {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Sha256 {}
and then
final MessageDigestModule extends AbstractModule {
@Provide
@Md5
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("MD5");
}
@Provide
@Sha256
Supplier<MessageDigest> provideMd5Digest() {
return () -> MessageDigest.getInstance("SHA-256");
}
}
And then finally:
@Inject
@Sha256
Supplier<MessageDigest> sha128DigestSupplier;
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Explore Related Topics
Save this library and start creating your kit