kandi background
Explore Kits

guice | lightweight dependency injection framework for Java 6 | Dependency Injection library

 by   google Java Version: 5.1.0 License: Apache-2.0

 by   google Java Version: 5.1.0 License: Apache-2.0

Download this library from

kandi X-RAY | guice Summary

guice is a Java library typically used in Programming Style, Dependency Injection applications. guice has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
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: [![build status](https://github.com/google/guice/workflows/continuous-integration/badge.svg)](https://github.com/google/guice/actions). mailing lists: [user mailing list](http://groups.google.com/group/google-guice) <br/>. put simply, guice alleviates the need for factories and the use of new in your java code. think of guice’s @inject as the new new. you will still need to write factories in some cases, but your code will not depend directly on them. your code will be easier to change, unit test and reuse in other contexts. guice embraces java’s type safe nature, especially when it comes to features introduced in java 5 such as generics and annotations. you might think of guice as filling in missing features for core java. ideally, the language itself would provide most of the same features, but until such a language comes along, we have guice. guice helps you design better apis, and the guice api itself sets a good example. guice is
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • guice has a highly active ecosystem.
  • It has 10791 star(s) with 1532 fork(s). There are 559 watchers for this library.
  • There were 1 major release(s) in the last 12 months.
  • There are 316 open issues and 815 have been closed. On average issues are closed in 127 days. There are 64 open pull requests and 0 closed requests.
  • It has a positive sentiment in the developer community.
  • The latest version of guice is 5.1.0
guice Support
Best in #Dependency Injection
Average in #Dependency Injection
guice Support
Best in #Dependency Injection
Average in #Dependency Injection

quality kandi Quality

  • guice has 0 bugs and 0 code smells.
guice Quality
Best in #Dependency Injection
Average in #Dependency Injection
guice Quality
Best in #Dependency Injection
Average in #Dependency Injection

securitySecurity

  • guice has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • guice code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
guice Security
Best in #Dependency Injection
Average in #Dependency Injection
guice Security
Best in #Dependency Injection
Average in #Dependency Injection

license License

  • guice is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
guice License
Best in #Dependency Injection
Average in #Dependency Injection
guice License
Best in #Dependency Injection
Average in #Dependency Injection

buildReuse

  • guice releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • guice saves you 186572 person hours of effort in developing the same functionality from scratch.
  • It has 74380 lines of code, 6309 functions and 647 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
guice Reuse
Best in #Dependency Injection
Average in #Dependency Injection
guice Reuse
Best in #Dependency Injection
Average in #Dependency Injection
Top functions reviewed by kandi - BETA

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.

  • Returns a scope using the specified key .
  • Get the injection points for a type .
  • Collects all declared methods for the given type .
  • Validates the given interface .
  • Handle the request .
  • Creates mapping between constructors and constructors .
  • Prepare the built - in converters .
  • Build trie .
  • Finds the appropriate injection point for a constructor .
  • Returns suggestions for the given key .

guice Key Features

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: [![Build Status](https://github.com/google/guice/workflows/continuous-integration/badge.svg)](https://github.com/google/guice/actions)

Mailing Lists: [User Mailing List](http://groups.google.com/group/google-guice) &lt;br/&gt;

License: [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0)

Create MessageDigest with Guice

copy iconCopydownload iconDownload
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

copy iconCopydownload iconDownload
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

copy iconCopydownload iconDownload
/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?

copy iconCopydownload iconDownload
@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

copy iconCopydownload iconDownload
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?

copy iconCopydownload iconDownload
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

copy iconCopydownload iconDownload
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?

copy iconCopydownload iconDownload
<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

copy iconCopydownload iconDownload
@Override protected void configure() {
  Names.bindProperties(binder(), System.getProperties());
}

Runtime value injection in Dagger vs. Guice

copy iconCopydownload iconDownload
@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) {
    /*...*/
  }

Community Discussions

Trending Discussions on guice
  • Create MessageDigest with Guice
  • Spring Boot Logging to a File
  • Java : io.protostuff.compiler.parser.ParserException: Can not load proto
  • OWL API NoSuchMethodError in saveOntology() call
  • Gerrit fails to start the service
  • AroundInvoke: Curious name?
  • Guice generic type injection
  • How to Manage JNDI Context In JUnit Tests?
  • Save HAR file without browsermodproxy
  • Wire collection of objects dynamically in Guice
Trending Discussions on guice

QUESTION

Create MessageDigest with Guice

Asked 2022-Mar-25 at 18:00

I'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:00

Edit

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;

Source https://stackoverflow.com/questions/71611712

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install guice

You can download it from GitHub, Maven.
You can use guice like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the guice component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Consider Popular Dependency Injection Libraries
Compare Dependency Injection Libraries with Highest Support
Compare Dependency Injection Libraries with Highest Quality
Compare Dependency Injection Libraries with Highest Security
Compare Dependency Injection Libraries with Permissive License
Compare Dependency Injection Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.