Reputation: 955
I want to make some of parts my JEE application independent from others ones using dependency inversion and dependency injection. Below is some code of main core part, that uses MyService, but is independent from other module that should provide implementation of MyService.
public interface MyService {
public void send(MyObject myObject);
}
.
@Stateless
@LocalBean
public class MyServiceWrapper implements MyService {
@Inject
private MyService myService;
@Override
public void send(MyObject myObject) {
myService.send(myObject);
}
}
To clarify:
Module A contains classes:
Module B contains implementation of MyService.
I want MyServiceWrapper to have injected implementation of MyService provided by module B, so module A can call implementation of MyService by using MyServiceWrapper, but in te same time module A is independent from module B.
The problem with above code, is that container do not know which implementation of MyService should be injected.
How it should be written so MyServiceWrapper, so it won't be injected to itself, but proper implementation (provided in other module) will be injected instead?
Upvotes: 0
Views: 61
Reputation: 230
The correct way would be to use what is known as a Qualifier
, one example from CDI would be the annotation @Named
, this would get rid of ambiguity for the container.
public interface MyService {
void send(MyObject myObject);
}
and the implementation of MyService
:
@Named("fromModuleA")
@ApplicationScoped
public class MyServiceWrapper implements MyService {
@Inject
@Named("fromModuleB")
private MyService someOtherBean;
@Override
public void send(MyObject myObject) {
this.someOtherBean.send(myObject);
}
}
@Named("fromModuleB")
@ApplicationScoped
public class SomeOtherBeanFromModuleB implements MyService{
@Override
public void send(MyObject myObject) {
// implementation
}
}
The @Inject
comes from a Java specification called CDI (Context and Dependency Injection), with this annotation it doesn't matter whether you use it on EJBs or CDI beans, but @EJB will only work with the EJB Container. Also note you don't really need the Interface MyService
at least not anymore but it's a good practice to code to the interface.
Upvotes: 1