Inject into a being injected class

58 views
Skip to first unread message

Balaraj V

unread,
Apr 18, 2017, 3:40:42 PM4/18/17
to google-guice

I'm using Google Guice for dependency injection in my application. I have a class structure like this,

Example is taken from here


This is my interface,

package com.journaldev.di.services;

@ImplementedBy(EmailService.class)
public interface MessageService {

    boolean sendMessage(String msg, String receipient);
}

Which I will implement here

package com.journaldev.di.services;

import javax.inject.Singleton;

//import com.google.inject.Singleton;

@Singleton
public class EmailService implements MessageService {

    public boolean sendMessage(String msg, String receipient) {
        //some fancy code to send email
        System.out.println("Email Message sent to "+receipient+" with message="+msg);
        return true;
    }
}

If I inject EmailService here.

package com.journaldev.di.consumer;

import javax.inject.Inject;

import com.journaldev.di.services.MessageService;

public class MyApplication {

    private MessageService service;

    @Inject
    public void setService(MessageService svc){
        this.service=svc;
    }

    public boolean sendMessage(String msg, String rec){
        //some business logic here
        return service.sendMessage(msg, rec);
    }
}

If suppose my EmailService class looked like this,

package com.journaldev.di.services;

import javax.inject.Singleton;

//import com.google.inject.Singleton;

@Singleton
public class EmailService implements MessageService {
    public EmailService(int someValue) {
         FancyEmailService fancyEmailService = new FancyEmailService(someValue);
    }
    public boolean sendMessage(String msg, String receipient) {
        fancyEmailService.doSomething();
        System.out.println("Email Message sent to "+receipient+" with message="+msg);
        return true;
    }
}

In order to test the above EmailService code, I need to inject FancyEmailService than instantiating from the constructor. How do I inject FancyEmailService into EmailService code? and still be able to inject EmailService into MyApplication.

I posted the same question in Stackoverflow could not find any answers. 

Stephan Classen

unread,
Apr 19, 2017, 12:50:04 AM4/19/17
to google...@googlegroups.com
You would need to bind the dependencies of your fancy email service. If those are configuration values like "url", "port" or similiar I recommend looking ate some of the 3rd party extensions which allow you to easily bind values from a properties file to a @Named singleton.

Maybe you find something at the apache onami project.
Reply all
Reply to author
Forward
0 new messages