How to Inject implementation in Guice 4.0 - java

I had this class as follows which works fine
#Singleton
public class EmpResource {
private EmpService empService;
#Inject
public EmpResource(EmpService empService) {
this.empService=empService;
}
}
public class EmpService {
public void getName(){..}
}
Now instead of using EmpService directly, I had to create an interface and EmpService implement that interface as follows.
public interface IEmpService{
void getName();
}
public class EmpServiceImpl implements IEmpService {
public void getName(){...}
}
So now my resource class has to use the interface but I am not sure how to reference the implementation it has to use.
#Singleton
public class EmpResource {
private IEmpService empService;
#Inject
public EmpResource(IEmpService empService) {
this.empService=empService;
}
}
I've seen this and I wasn't sure where my binding should go. (This is my first project related to Guice so I am a total newbie).
This is the error that came "No implementation for com.api.EmpService was bound." which is totally understandable but not sure how to fix it.
I appericiate your help.
FYI: I am using Dropwizard application.

You would configure your module similar to this:
public class YourModule extends AbstractModule {
#Override
protected void configure() {
bind(EmpService.class).to(EmpServiceImpl.class);
// ....
}
}

you also have to add a Provide Methode for your EmpServiceImpl class
public class MyModule extends AbstractModule {
#Override
protected void configure() {
bind(IEmpService.class).to(EmpServiceImpl.class);
}
#Provides
EmpServiceImpl provideEmpServiceImpl() {
// create your Implementation here ... eg.
return new EmpServiceImpl();
}
}

Related

How to use Spring Constructor DI in classes implementing an interface

So I want to achieve something like this:
#Component
public class ComponentA {
public void doThis(){};
}
#Component
public class ComponentB {
public void doThat(){};
}
public interface MyInterface {
void doSomething();
}
public class MyInterfaceImplA implements MyInterface {
private final ComponentA componentA;
#Inject
public MyInterfaceImplA(ComponentA componentA){
this.componentA = componentA;
}
public void doSomething(){
componentA.doThis();
}
}
public class MyInterfaceImplB implements MyInterface {
private final ComponentB componentB;
#Inject
public MyInterfaceImplB(ComponentB componentB) {
this.componentB = componentB;
}
public void doSomething() {
componentB.doThat();
}
}
What I basically want is to inject different components into different classes implementing the same interface.
My question is if there is a good way to set this architecture up in this or a similar way? Or is there a pattern to achieve this in a better way?

Defining bean with two possible implementations

So far, I had a very simple bean definition that looked like this:
#Bean
#Conditional(value=ConditionClass.class)
SomeInterface myMethodImpl(){
return new ImplementationOne();
}
However, I now have situation where additional implementation class has been added, let's call it ImplementationTwo, which needs to be used instead of ImplementationOne when the option is enabled in configuration file.
So what I need is something like this:
#Bean
#Conditional(value=ConditionClass.class)
SomeInterface myMethodImpl(){
return context.getEnvironment().getProperty("optionEnabled") ? new
ImplementationOne() : new ImplementationTwo();
}
Basically a way to instantiate correct implementation at bean definition time based on the configuration value. Is this possible and can anyone please provide an example? Thanks
It is possible to implement this without using #Conditional.
Assuming you have a Interface SomeInterface and two implementations ImplOne ImplTwo:
SomeInterface.java
public interface SomeInterface {
void someMethod();
}
ImplOne.java
public class ImplOne implements SomeInterface{
#Override
public void someMethod() {
// do something
}
}
ImplTwo.java
public class ImplTwo implements SomeInterface{
#Override
public void someMethod() {
// do something else
}
}
Then you can control which implementation is used in a configuration class like this:
MyConfig.java
#Configuration
public class MyConfig {
#Autowired
private ApplicationContext context;
#Bean
public SomeInterface someInterface() {
if (this.context.getEnvironment().getProperty("implementation") != null) {
return new ImplementationOne();
} else {
return new ImplementationTwo();
}
}
}
Make sure that the component scan of spring finds MyConfig. Then you can use #Autowired to inject the right implementation anywhere else in your code.
I think you are doing it wrong.
You should use #Conditional() on your implementation and not on your Interface.
Here is how I would do it :
The interface you will use on your code.
MyInterface.java
public interface MyInterface {
void myMethod();
}
The first implementation :
MyInterfaceImplOne.java
#Bean
#Conditional(MyInterfaceImplOneCondition.class)
public class MyInterfaceImplOne implements MyInterface {
void myMethod(){
// dosmthg
}
}
MyInterfaceImplOneCondition.java
public class MyInterfaceImplOneCondition implements Condition {
#Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("optionEnabled")
}
}
And for the 2nd implementation :
MyInterfaceImplTwo.java
#Bean
#Conditional(MyInterfaceImplTwoCondition.class)
public class MyInterfaceImplTwo implements MyInterface {
void myMethod(){
// dosmthg 2
}
}
MyInterfaceImplTwoCondition.java
public class MyInterfaceImplTwoCondition implements Condition {
#Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return !context.getEnvironment().getProperty("optionEnabled")
}
}
In that case, you now just have to call the interface, and Spring will inject the bean corresponding to the right condition.
Hope it is what you are looking for, and I was clear enough!

One interface multipe implementations. How get the right one at runtime

Lets say I have an Object with one boolean field.
public class AnyPojo {
private boolean b;
}
An interface DoAnything
public interface DoAnything {
void doAnything();
}
And two #Service annotated implementations of DoAnything
public class DoAnythingOneImpl implements DoAnything {
#Override
public void doAnything(){
//..
}
}
public class DoAnythingTwoImpl implements DoAnything {
#Override
public void doAnything(){
//..
}
}
In another #Service class the boolean field of AnyPojo determines which implementation of DoAnything should be called. How can I achive that? I can use ApplicationContext here and make the decision like below. But not sure if there are better ways.
#Service
public class AnotherServiceImpl implements AnotherService {
#Autowire
private ApplicationContext context;
#Override
public void anotherDoing(AnyPojo anyPojo) {
if(anyPojo.getB()){
context.getBean(DoAnythingOneImpl.class).doAnything();
} else{
context.getBean(DoAnythingTwoImpl.class).doAnything();
}
}
First things first, if your class requires particular implementations, why don't you simply inject these classes?
If you have several implementations of an interface, you have to inform Spring framework which one you would like to inject into a class. You can distinguish implementations by their unique bean names:
#Service("oneImpl")
public class DoAnythingOneImpl implements DoAnything {
#Override
public void doAnything(){
//..
}
}
#Service("twoImpl")
public class DoAnythingTwoImpl implements DoAnything {
#Override
public void doAnything(){
//..
}
}
And then inject both instances to the client service by marking which implementation should by assign to particular fields:
#Service
public class AnotherServiceImpl implements AnotherService {
#Autowire
#Qualifier("oneImpl")
private DoAnything doAnythingOneImpl;
#Autowire
#Qualifier("twoImpl")
private DoAnything doAnythingTwoImpl;
#Override
public void anotherDoing(AnyPojo anyPojo) {
if(anyPojo){
doAnythingOneImpl.doAnything();
} else{
doAnythingTwoImpl.doAnything();
}
}
Note that I would not call a service component from another service component to make sure I avoid potential redundant cycle in the future.
I would keep the following flow :
Controller ---canCall---> Services ---canCall---> Repositories
And if you need services with a more complex logic, then introduces the concept of Facade
Controller ---canCall---> Facades ---canCall---> Services ---canCall---> Repositories
However, here is a solution :
#Service("myServiceOne")
public class DoAnythingOneImpl implements DoAnything {
#Override
public void doAnything(){
//..
}
}
#Service("myServiceTwo")
public class DoAnythingTwoImpl implements DoAnything {
#Override
public void doAnything(){
//..
}
}
You can autowire both services and choose the best one based on your boolean :
#Service
public class AnotherServiceImpl implements AnotherService {
#Autowired
#Qualifier("myServiceOne")
private DoAnything serviceOne;
#Autowired
#Qualifier("myServiceTwo")
private DoAnything serviceTwo;
#Override
public void anotherDoing(AnyPojo anyPojo) {
if(anyPojo){
serviceOne.doAnything();
} else{
serviceTwo.doAnything();
}
}
}

How to collect several interfaces into a Collection in HK2?

I have my AbstractBinder and I bind several classes with the same interface. Let's say I bind Fish and Cat which both implement Animal interface.
What is the easiest/proper way of injecting them into a bean which takes Collection<Animal> ?
PS: Spring has equivalent in simply #Autowire List<Animal> and the collection is created and populated by Spring.
HK2 has IterableProvider<T>, as mentioned here in the documentation. You can get the service by name, by qualifier annotation, or just iterate over them, as it's an Iterable. Just for fun, here is a test.
public class IterableProviderTest {
public static interface Service {}
public static class ServiceOne implements Service {}
#QualAnno
public static class ServiceTwo implements Service {}
#Qualifier
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
public static #interface QualAnno {
public static class Instance
extends AnnotationLiteral<QualAnno> implements QualAnno {
public static QualAnno get() {
return new Instance();
}
}
}
public class Binder extends AbstractBinder {
#Override
protected void configure() {
bind(ServiceOne.class).to(Service.class).named("one");
bind(ServiceTwo.class).to(Service.class).qualifiedBy(QualAnno.Instance.get());
}
}
#Inject
private IterableProvider<Service> services;
#Test
public void test_IterableProvider() {
ServiceLocator locator = ServiceLocatorUtilities.bind(new Binder());
locator.inject(IterableProviderTest.this);
assertEquals(2, services.getSize());
Service serviceOne = services.named("one").get();
assertTrue(serviceOne instanceof ServiceOne);
Service serviceTwo = services.qualifiedWith(QualAnno.Instance.get()).get();
assertTrue(serviceTwo instanceof ServiceTwo);
}
}
UPDATE
For a List<Service> (to avoid HK2 InterablProvider), the only think I can think of is to use a Factory and inject the IterableProvider into it, and from there return the list. For example
public class Binder extends AbstractBinder {
#Override
protected void configure() {
...
bindFactory(ListServiceFactory.class).to(new TypeLiteral<List<Service>>(){});
}
}
public static class ListServiceFactory implements Factory<List<Service>> {
#Inject
private IterableProvider<Service> services;
#Override
public List<Service> provide() {
return Lists.newArrayList(services);
}
#Override
public void dispose(List<Service> t) {}
}
Yeah it's a little bit of extra work.
In the latest release of hk2 (2.4.0) you can
#Inject Iterable<Foo> foos;
That allows you to keep your pojo's without any hk2 API in them.
For more information see: Iterable Injection

Injecting method interceptors in Guice

I've searched all over the web for it and everyone (including) google suggests using requestInjection() but I still don't understand how to use it. I have a class that implements Method Interceptor:
public class CacheInterceptor implements MethodInterceptor {
private ILocalStore localStore;
private IRemoteStore remoteStore;
private CacheUtils cacheUtils;
public CacheInterceptor() {
}
#Inject
public CacheInterceptor(ILocalStore localStore, CacheUtils cacheUtils, IRemoteStore remoteStore) {
this.localStore = localStore;
this.cacheUtils = cacheUtils;
this.remoteStore = remoteStore;
}
}
And I have 3 classes that extends AbstractModule.
public class CacheUtilModule extends AbstractModule {
#Override
protected void configure() {
bind(CacheUtils.class);
}
}
public class LocalCachingModule extends AbstractModule {
#Override
public void configure() {
bind(ILocalStore.class).to(LocalStore.class);
}
}
public class RedisCachingModule extends AbstractModule {
#Override
protected void configure() {
bind(IRemoteStore.class).to(RemoteStore.class);
}
}
And I did the following for binding the interceptor
public class RequestScopedCachingModule extends AbstractModule {
#Override
public void configure() {
install(new CacheUtilModule());
install(new LocalCachingModule());
install(new RedisCachingModule());
MethodInterceptor interceptor = new CacheInterceptor();
requestInjection(interceptor);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(Cacheable.class),
interceptor);
}
}
So basically, I want to inject the localStore, remoteStore, and cacheUtils in my MethodInterceptor with my own implementation mapped out in my 3 modules. But this didn't work. I guess I am just confused with requestInjection(). In the documentation, requestInjection does this
Upon successful creation, the Injector will inject instance fields and methods of the given object.
But where do we specify the mapping between the interface and the implementation class? How can I get what I wanted to do to work?
requestInjection will only inject fields and methods - it won't invoke the constructor and doesn't know anything about the #Inject annotations on your constructor. If you add #Inject to all of your fields your code should work as you expect.

Categories