Override JPA persistence unit properties in code with Google Guice

To override properties from persistence.xml through code while using it with Google guice. One can read the properties from different source and add those properties while installing JpaPersistModule. Following is the sample Properties persistenceUnit = new Properties(); persistenceUnit.put("javax.persistence.jdbc.url", "jdbc:mysql://192.168.9.102/MyDB"); persistenceUnit.put("javax.persistence.jdbc.user", "myuser"); persistenceUnit.put("javax.persistence.jdbc.password", "mypassword"); Injector injector = Guice.createInjector(new JpaPersistModule("my-persistence-unit").properties(persistenceUnit)); One can chose to read this configuration from some other file and install JpaPersistModule with those properties. This could be useful to override database url for test and production. [Read More]

Set Servlet RequestScope Guice dependencies

Set some commonly used dependencies which are dependent on some parameter of HTTP Request. The most common use case is to add logged in user context in request scope from session id inside filter. To do that you need to bind such a dependency inside your ServletModule like following. bind(User.class).annotatedWith(Names.named("user")).to(User.class).in(ServletScopes.REQUEST); You are just binding a given User.class with @Named("user") annotation inside RequestScope. Now you have to take care of setting required value when request is made. [Read More]

Access annotated dependencies through injector instance

Following sample will demonstrate how to access guice dependency annotated with some annotation through direct Guice injector instance. Bar.java import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import com.google.inject.BindingAnnotation; @Retention(RetentionPolicy.RUNTIME) @BindingAnnotation public @interface Bar { } Foo.java import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import com.google.inject.BindingAnnotation; @Retention(RetentionPolicy.RUNTIME) @BindingAnnotation public @interface Foo { } TestDepdency.java public interface TestDepdency { String getValue(); } FooTestDependencyImpl.java public class FooTestDependencyImpl implements TestDepdency { @Override public String getValue() { return "Foo"; } } BarTestDependencyImpl. [Read More]

Mulitple persistence Unit with Guice

If you want to use Guice with multiple persistence Unit. Then its not much difficult task to do it, Guice's official wiki document says it all refer. But I feel it has missed out most important part from it i.e. to expose dependencies, if those dependencies need to be used outside the scope of give PrivateModule. Note : I have created a complete working sample with multiple persistent unit refer - https://github. [Read More]