Ritesh Singh Ritesh Singh - 1 month ago 13
Java Question

Unable to Inject Configuration in normal utility classes Play Framework 2.5.x

I am unable to Inject Configuration in normal utility classes ,it works fine in controller class.

@Inject
Configuration configuration

public class EmailService {
public static boolean sendEmail(final AppUser appUser,final String mailString,String subject) {
final Properties props = new Properties();
final String auth = Play.application().configuration().getString("mail.smtp.auth‌​")
final String starttls = Play.application().configuration().getString("mail.smtp.star‌​ttls.enable");
}
}


Actually I want to remove Depricated Play.application() and want to use Configuration for that I want to Inject Configuration in this class.

Answer

Dependency injection frameworks inject dependencies when constructing instances of objects, so if you want a method to use an injected component it has to be non-static.

You want to do something like this, making your sendEmail method non-static, and providing an interface:

@ImplementedBy(EmailServiceImpl.class)
public interface EmailService {
    void sendEmail(AppUser appUser, String mailString, String subject);
}

@Singleton
public class EmailServiceImpl implements EmailService {
    private final Configuration config;

    @Inject
    public EmailServiceImpl(Configuration config) {
        this.config = config;
    }

    public void sendEmail(AppUser appUser, String mailString, String subject) {
        final Properties props = new Properties(); 
        final String auth = config.getString("mail.smtp.auth‌​")
        final String starttls = config.getString("mail.smtp.star‌​ttls.enable");
    }
}

Then inject an EmailService instance into your controller constructors.

Note: this uses @ImplementedBy for simplicity but you could also configure the binding in your Guice module, allowing you to mock it in tests.

Comments