Suppose the following code:
#Service
public class SearchService {
#Autowired
DependencyService dependencyService;
}
#Service
public class DependencyService {
private final Util util;
DependencyService(Util util){
this.util = util;
execute();
}
public void execute(){
util.execte();
}
}
#Component
public class ConcreteUtil implements Util{
#Override
public void execte() {
System.out.println("I'm the first concrete Util");
}
}
#Component
public class SecondConcreteUtil implements Util{
#Override
public void execte() {
System.out.println("I'm the second concrete Util");
}
}
In Plain Java I can do something like this:
public class SearchService {
DependencyService first = new DependencyService(new ConcreteUtil());
DependencyService second = new DependencyService(new SecondConcreteUtil());
}
But in Spring, it's not resolved by the client. We instruct Spring which bean to take from inside DependencyService:
DependencyService(#Qualifier("concreteUtil")Util util){
this.util = util;
execute();
}
And not like that:
#Autowired
#Qualifier("concreteUtil")
DependencyService dependencyService;
Why? To me this approach sounds like the opposite of decoupling. What do I miss? And how can Plain Java's result be achieved?
Edit:
I want this behaviour
public class SomeSerice {
DependencyService firstConcrete = new DependencyService(new ConcreteUtil());
}
public class OtherService {
DependencyService SecondConcrete = new DependencyService(new SecondConcreteUtil());
}
So I can reuse the code
You can declare multiple beans of type Dependency service inside some configuration class, like
#Qualifier("ConcreteUtilDepService")
#Bean
public DependencyService concreteUtilDS(#Qualifier("ConcreteUtil")Util util){
return new DependencyService (util);
}
I am trying to inject a vertx instance
public ServiceBinder(Vertx vertx) {
this.vertx = vertx;
}
I am binding like this
#Override
protected void configure() {
bind(Vertx.class).toInstance(this.vertx);
}
And I am invoking injection like this
public class BaseVerticle extends AbstractVerticle{
#Override
public void start(Future<Void> startFuture) {
Guice.createInjector(new ServiceBinder(vertx)).injectMembers(this);
}
}
Now I try to inject this in another class
public class DelegateFactory {
#Inject
private Vertx vertx;
}
However here the value of vertx is null. Do I need inject DelegateFactory too?
I tried annotating DelegateFactory with #Singleton, but it did not help
Make sure that :
Your ServiceBinder class extends com.google.inject.AbstractModule
Your DelegateFactory is binded in your ServiceBinder or another guice's AbstractModule subclass like that :
bind(DelegateFactory.class).in(Singleton.class)
or
bind(DelegateFactory.class).toInstance(...)
P.S : it's better to be fail-fast in your ServiceBinder constructor :
import static java.util.Objects.requireNonNull;
public ServiceBinder(Vertx vertx) {
this.vertx = requireNonNull(vertx, "vertx must not be null");
}
I have an interface/implementation like so:
public interface Processor {
void processMessage(Message m);
}
#Component
public class FooAProcessor implements Processor {
private FooA fooA;
public FooAProcessor(FooA fooA) {
this.fooA = fooA;
}
#Override
public void processMessage(Message m) {
//do stuff
}
}
#Component
public class FooBProcessor implements Processor {
private FooA fooA;
public FooBProcessor(FooA fooA) {
this.fooA = fooA;
}
#Override
public void processMessage(Message m) {
//do stuff
}
}
The FooA bean is simple, like this:
#Component
public class FooA {
//stuff
}
And the message class:
public class Message {
private Class clazz;
}
I am pulling messages off a queue. I need to provide a concrete Processor to handle the different types of messages appropriately. Here's the message receiver:
public class MessageReceiver {
public void handleMessage(Message m) {
Processor processor = //get concrete implementation from Message clazz
processor.processMessage(m);
}
}
How exactly can I use the class name/object to define a concrete implementation of Processor?
My first thought was to develop some sort of a factory that takes in a class and provides the concrete implementation. Something like this:
#Component
public class ProcessorFactory {
private FooAProcessor fooAProcessor;
private FooBProcessor fooBProcessor;
public ProcessorFactory(FooAProcessor fooAProcessor, FooBProcessor fooBProcessor) {
this.fooAProcessor = fooAProcessor;
this.fooBProcessor = fooBProcessor;
}
public Processor getFactory(Class clazz) {
if(clazz.isAssignableFrom(FooAProcessor.class)) {
return fooAProcessor;
}
}
}
Or to use the application context like this:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getBean(clazz);
Is this the best way to go about this problem? Is there a better practice?
You can inject ApplicationContext into your factory and get beans from there:
#Component
public class Factory {
#Autowired ApplicationContext applicationContext;
public Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
}
Or you can put your processors into map and get them from it:
#Component
public class ProcessorFactory {
private final Processor fooAProcessor;
private final Processor fooBProcessor;
private final Map<Class<T extends Processor>, Processor> beanMap;
public ProcessorFactory (Processor fooAProcessor, Processor fooBProcessor) {
this.fooAProcessor = fooAProcessor;
this.fooBProcessor = fooBProcessor;
this.beanMap = new HashMap(2);
}
#PostConstruct
public void init() {
beanMap.put(FooAProcessor.class, fooAProcessor);
beanMap.put(FooBProcessor.class, fooBProcessor);
}
public Processor getProcessor(Class<T extends Processor> clazz) {
return beanMap.get(clazz);
}
}
I recommend to not rely on class when working with spring context but use beanNames instead.
Java 8, Guice 4.0 and Akka 2.3.9 here. I am trying to figure out how to annotate my actor classes with JSR330-style #Inject annotations, and then wire them all up via Guice.
But literally every single article I have read (some examples below) either uses Scala code examples, a criminally-old version of Guice, or a criminally-old version of Akka:
Let It Crash
Scala-Guice
So, given the following Guice module:
public interface MyService {
void doSomething();
}
public class MyServiceImpl implements MyService {
#Override
public void doSomething() {
System.out.println("Something has been done!");
}
}
public class MyActorSystemModule extends AbstractModule {
#Override
public void configure() {
bind(MyService.class).to(MyServiceImpl.class);
}
}
And given the FizzActor that gets injected with a MyService:
public class FizzActor extends UntypedActor {
private final MyService myService;
#Inject
public FizzActor(MyService myService) {
super();
this.myService = myService;
}
#Override
public void onReceive(Object message) {
// .. Do fizz stuff inside here.
}
}
Then I ask: How do I rig up MyActorSystemModule to create instances of FizzActor and properly inject them with Java (not Scala!)?
Please note: FizzActor is not the only actor in my actor system!
Use Creator to create ActorRefs in provider methods of your guice module. To distinguish between the different ActorRefs, which are untyped, use annotations on your provider methods and injection points as you would any guice system. For example,
In your guice module:
#Override
protected void configure() {
bind(ActorSystem.class).toInstance(ActorSystem.apply());
bind(FizzService.class).toInstance(new FizzServiceImpl());
}
#Provides #Singleton #Named("fizzActor")
ActorRef serviceActorRef(final ActorSystem system, final FizzService fizzService) {
return system.actorOf(Props.create(new Creator<Actor>() {
#Override
public Actor create() throws Exception {
return new FizzActor(fizzService);
}
}));
}
Then to use the actor service, inject a specific ActorRef:
class ClientOfFizzActor {
#Inject
ClientOfFizzActor(#Named("fizzActor") ActorRef fizzActorRef) {..}
}
It looks cleaner if the Props.create(..) clause is a static factory method in your actor class.
Unless you are trying to bind UntypedActor to FizzActor, then you can just inject it into other classes as is:
class SomeOtherClass {
#Inject
public SomeOtherClass(FizzActor fizzActor) {
//do stuff
}
}
If you're trying to bind it to the interface, you'll need to specifically do that in the module:
public class MyActorSystemModule extends AbstractModule {
#Override
public void configure() {
bind(MyService.class).to(MyServiceImpl.class);
bind(UntypedActor.class).to(FizzActor.class);
}
}
Edit:
What about using #Named to distinguish the UntypedActor, e.g.:
class SomeOtherClass {
#Inject
public SomeOtherClass(#Named("fizzActor")UntypedActor fizzActor, #Named("fooActor") UntypedActor fooActor) {
//do stuff
}
}
Then in your module you could do the akka lookups:
public class MyActorSystemModule extends AbstractModule {
ActorSystem system = ActorSystem.create("MySystem");
#Override
public void configure() {
bind(MyService.class).to(MyServiceImpl.class);
}
#Provides
#Named("fizzActor")
public UntypedActor getFizzActor() {
return system.actorOf(Props.create(FizzActor.class), "fizzActor");
}
#Provides
#Named("fooActor")
public UntypedActor getFooActor() {
return system.actorOf(Props.create(FooActor.class), "fooActor");
}
}
Use an akka Creator:
public class GuiceCreator<T> implements Creator<T> {
Class<T> clz;
Module module;
/*Constructor*/
public T create() {
Injector injector = Guice.createInjector(this.module);
return injector.getInstance(this.clz);
}
}
Then use Props.create with your shiny new guice-based creator.
Disclaimer: I don't actually know Akka, the mentioned information comes from browsing the documentation and JavaDoc.
In case anyone found this question, you need to use IndirectActorProducer, I referred to the Spring example and changed it to use Guice instead.
/**
* An actor producer that lets Guice create the Actor instances.
*/
public class GuiceActorProducer implements IndirectActorProducer {
final String actorBeanName;
final Injector injector;
final Class<? extends Actor> actorClass;
public GuiceActorProducer(Injector injector, String actorBeanName, Class<? extends Actor> actorClass) {
this.actorBeanName = actorBeanName;
this.injector = injector;
this.actorClass = actorClass;
}
#Override
public Actor produce() {
return injector.getInstance(Key.get(Actor.class, Names.named(actorBeanName)));
}
#Override
public Class<? extends Actor> actorClass() {
return actorClass;
}
}
In the module
public class BookingModule extends AbstractModule {
#Override
protected void configure() {
// Raw actor class, meant to be used by GuiceActorProducer.
// Do not use this directly
bind(Actor.class).annotatedWith(
Names.named(BookingActor.ACTOR_BEAN_NAME)).to(
BookingActor.class);
}
#Singleton
#Provides
#Named(BookingActor.ACTOR_ROUTER_BEAN_NAME)
ActorRef systemActorRouter(Injector injector, ActorSystem actorSystem) {
Props props = Props.create(GuiceActorProducer.class, injector, BookingActor.ACTOR_BEAN_NAME, actorClass);
actorSystem.actorOf(props.withRouter(new RoundRobinPool(DEFAULT_ROUTER_SIZE)), BookingActor.ACTOR_ROUTER_BEAN_NAME);
}
}
So I have been playing around with Akka and Guice recently alot and I feel that those two don't play too well together.
What I suggest is you take a similar approach what Play is doing.
Kutschkem's answer comes closest to that.
use the ActorCreator interface
make sure you have an argumentless Creator. Don't try to do #AssisstedInject in your Creator as this will imply that you will need a new creator for every Actor that you want to create. Personally I believe that initializing this in the actor is better done through messaging.
let the ActorCreator consume an injector such that you can easily create the Actor Object within the Creator.
Here is a code example using current Akka 2.5. This is the preferred setup we chose for our Akka 2.5 deployment. For brevity I did not provide the Module, but it should be clear from the way the Members are injected, what you want to provide.
Code:
class ActorCreator implements Creator<MyActor>
#Inject
Injector injector;
public MyActor create() {
return injector.getInstance(MyActor.class);
}
}
class MyActor extends AbstractActor {
#Inject
SomeController object;
#Nullable
MyDataObject data;
public ReceiveBuilder createReceiveBuilder() {
return receiveBuilder()
.match(MyDataObject.class, m -> { /* doInitialize() */ })
.build();
}
}
class MyParentActor extends AbstractActor {
#Inject
ActorCreator creator;
void createChild() {
getContext().actorOf(new Props(creator));
}
void initializeChild(ActorRef child, MyDataObject obj) {
child.tell(obj);
}
}
Generic Akka Guice integration without dependency on Play,
keeping in mind, not the only actor should be created in the actor system.
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import com.google.inject.AbstractModule;
import com.google.inject.Provider;
import com.google.inject.name.Names;
public abstract class AkkaGuiceModule extends AbstractModule {
protected <T extends Actor> void bindActor(Class<T> actorClass, String name) {
bind(actorClass);
Provider<ActorSystem> actorSystemProvider = getProvider(ActorSystem.class);
Provider<T> actorProvider = getProvider(actorClass);
bind(ActorRef.class)
.annotatedWith(Names.named(name))
.toProvider(ActorRefProvider.of(actorSystemProvider, actorProvider, name))
.asEagerSingleton();
}
}
Generic ActorRefProvider to create ActorRef for each Actor
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.japi.Creator;
import com.google.inject.Provider;
import lombok.Value;
#Value(staticConstructor = "of")
public class ActorRefProvider<T extends Actor> implements Provider<ActorRef> {
private Provider<ActorSystem> actorSystemProvider;
private Provider<T> actorProvider;
private String name;
public final class ActorCreator implements Creator<Actor> {
#Override
public Actor create() {
return actorProvider.get();
}
}
#Override
public ActorRef get() {
return actorSystemProvider.get().actorOf(Props.create(new ActorCreator()), name);
}
}
Usage example
import akka.actor.ActorSystem;
import com.google.inject.Provides;
import com.typesafe.config.Config; // optional
public class MyAkkaModule extends AkkaGuiceModule {
#Provides
#Singleton
ActorSystem actorSystem(Config config) {
return ActorSystem.create("actor-system-name", config);
}
#Override
protected void configure() {
bindActor(SomeActor1.class, "actorName1");
bindActor(SomeActor2.class, "actorName2");
}
}
The title describes my problem.
E.g.
public class EntryDAOModule extends AbstractModule {
#Override
protected void configure() {
bind(EntryDAO.class).to(EntryDTOMongoImpl.class); // what should this be?
}
}
As shown, what should be the parameter to .to, given the below:
public class GenericDAOMongoImpl<T, K extends Serializable> extends BasicDAO<T, K> {
public GenericDAOMongoImpl(Class<T> entityClass) throws UnknownHostException {
super(entityClass, ConnectionManager.getDataStore());
}
}
public class EntryDAOMongoImpl extends GenericDAOMongoImpl<EntryDTOMongoImpl, ObjectId> implements EntryDAO<EntryDTOMongoImpl> {
private static final Logger logger = Logger.getLogger(EntryDAOMongoImpl.class);
#Inject
public EntryDAOMongoImpl(Class<EntryDTOMongoImpl> entityClass) throws UnknownHostException {
super(entityClass);
}
...
}
How can I instantiate the EntryDAOMongoImpl class like so:
Injector injector = Guice.createInjector(new EntryDAOModule());
this.entryDAO = injector.getInstance(EntryDAO.class); // what should this be?
What you are going to need here is to create a factory. Using assisted injection can help you here.
You can see my previous post regarding assisted injection
but here's the exact solution for your case:
EntryDAOMongoImpl:
public class EntryDAOMongoImpl extends GenericDAOMongoImpl<EntryDTOMongoImpl, ObjectId> implements EntryDAO<EntryDTOMongoImpl> {
private static final Logger logger = Logger.getLogger(EntryDAOMongoImpl.class);
#Inject
public EntryDAOMongoImpl(#Assisted Class<EntryDTOMongoImpl> entityClass) throws UnknownHostException {
super(entityClass);
}
...
}
Factory:
public interface EntryDAOFactory {
public EntryDAOMongoImpl buildEntryDAO(Class<EntryDTOMongoImpl> entityClass);
}
Module:
public class EntryDAOModule extends AbstractModule {
#Override
protected void configure() {
//bind(EntryDAO.class).to(EntryDAOMongoImpl.class); // what should this be?
FactoryModuleBuilder factoryModuleBuilder = new FactoryModuleBuilder();
install(factoryModuleBuilder.build(EntryDAOFactory.class));
}
}
Usage:
Injector injector = Guice.createInjector(new EntryDAOModule());
EntryDAOFactory factory = injector.getInstance(EntryDAOFactory.class);
this.entryDAO = factory.buildEntryDAO(entityClass);
If you are going to be using the EntryDAOMongoImpl as a singelton (natural usage of a singleton imo) then you can do the following without assisted injection within your module:
public class EntryDAOModule extends AbstractModule {
#Override
protected void configure() {
EtnryDTOMongoImpl dto = new EntryDTOMongoImpl(TargetEntry.class); //guessing here
bind(EntryDAO.class).toInstance(new EntryDAOMongoImpl(dto)); // singleton
}
}
Let me know if that helps