Play Framework Dependency Injection - java

I've been looking all over Google to find some useful information on how to use Guice/Spring DI in Play Framework 2.1
What I want to do is to Inject several Services in some DAO's and vice versa.
Just need some clarification on this - With play 2.1, do you have to use an # annotation within the routes file for DI?
I've looked at this guide here - https://github.com/playframework/Play20/blob/master/documentation/manual/javaGuide/main/inject/JavaInjection.md
and applied the following steps creating a Global class in app and adding the GUICE dependencies in Build.scala but keep on getting a null pointer exception when invoking on the injected object.
Has anyone been able to get DI working in Play 2.1 using Guice? I've seen examples across the internet but they all seem to be using DI within the controller.

I noticed you are using Java. Here is how I got it to work for injecting into a controller.
First, I created the following 4 classes :
MyController:
package controllers;
import play.mvc.*;
import javax.inject.Inject;
public class MyController extends Controller {
#Inject
private MyInterface myInterface;
public Result someActionMethodThatUsesMyInterface(){
return ok(myInterface.foo());
}
}
MyInterface:
package models;
public interface MyInterface {
String foo();
}
MyImplementation2Inject:
package models;
public class MyImplementation2Inject implements MyInterface {
public String foo() {
return "Hi mom!";
}
}
MyComponentModule:
package modules;
import com.google.inject.AbstractModule;
import models.MyInterface;
import models.MyImplementation2Inject;
public class ComponentModule extends AbstractModule {
#Override
protected void configure() {
bind(MyInterface.class).
to(MyImplementation2Inject.class);
}
}
Now the final part, that took me a silly long time to figure out, was to register the module. You do this by adding the following line to the end of the application.conf file, which is located in the conf directory:
play.modules.enabled += "modules.MyComponentModule"
I hope this was helpful to you. :)

I use cake pattern and my own version of Global overriding getControllerInstance
https://github.com/benjaminparker/play-inject
Cheers
Ben

Sorry, this is a late response, but here's our example
https://github.com/typesafehub/play-guice

Have you tried using some different approach to DI than Guice?
We also tried implementing a project with Guice or Spring but ended in registering our dependencies in objects that implement trait such as:
trait Registry {
def userDao: UserDao
...
}
object Registry {
var current: Registry = _
}
object Environnment {
object Dev extends Registry {
val userDao = ...
//implement your environment for develpment here
}
object Test extends Registry {
val userDao = ...
//implement your ennviroment for tests here e.g. with mock objects
}
}
Another good approach wich might fit for you is the cake pattern (just google for it).

Related

SpringBoot #Autowire why does this example work?

I have created this class:
import org.springframework.stereotype.Component;
...
#Component("notTheNameTestMe") //shouldnt this only work with testMe ?
public class TestMe {
public void showMsg() {
System.out.println("Autowiring works");
}
}
And I'm using it this way in a second class (or better: controller):
import com.example.TestMe; //shouldnt this be not necessary with autowire? But getting error else...
...
#Autowired
private TestMe testMe;
...
this.testMe.showMsg();
But this works perfectly (so maybe Im not really using autowire here?), it even works if I rename the whole TestMe class to TestMeSomething (if I adjust the import in the second class)
I dont really understand what #Autowired does. I thought it just scans for SpringBoot Components (which are named by the string in #Component() and when it finds a match it Injects the dependancy. But in my example the match is impossible and I still can see the message "Autowiring works" in the console. This shouldnt be like this if I would really use autowire here or? What am I understanding in a wrong way? What is the difference to using new TestMe() then? I have the dependancy already with the import or? So not a real dependancy injection, or?
Spring is not operating on the name in the #Component annotation. Rather it's using the name of the class. It's simply finding a class named TestMe because that's the type of the variable you've annotated with #Autowired.

Usage of non public classes in spring java-based config

It seems to be a simple question but yet i couldn't find clear answer while searching documentation and forums. I'm migrating from xml to java-based config (Spring 5.1.9). Due to some legacy restrictions in xml config i need to create a bean from some side library's non public class:
SampleClass.class
package side.library
class SampleClass {
//... some code here
}
context.xml
...
<bean id = "sampleId" class "side.library.SampleClass">
...
And this works fine since Spring uses reflection inside and it creates bean without any problems at compile/runtime, but in java-based config usage of such class leads to an access error:
package my.configuration;
import side.library.SampleClass; // 'side.library.SampleClass' is not public in 'side.library'. Cannot be accessed from outside package
#Configuration
public class JavaConfiguration{
#Bean
public SampleClass sampleClass() {
return new SampleClass(); // same error text
}
}
So, what is the proper way to deal with this sutiation? Using reflection libs in #Configuration class to reach this class seems to be a bad idea.
just a workaround: create a wrapper class in the outer project in the same package and use this class in your configuration.
package com.legacy;
public class Wrapper {
private LegacyImpl legacyImpl;
public Wrapper()
this.legacyImpl = new LegacyImpl();
}
public void wrappedMethod() {
this.legacyImpl.wrappedMethod();
}
}

How can I use google guice DI outside of testNG test classes in a testNG based framework?

it is very simple to implement injection of objects into a testNG test class, it is handled mostly for us, however how can I build google guice DI into my framework and use it for classes which are not necessarily tests?
I want to inject using simple dependency injection for dependencies of my Page Object classes, these are nothing really to do with testNG, so how can we get the dependencies initialized for those?
Here is a simple example piece of code I want to replace:
public class HeaderComponent extends AbstractBasePageObject {
private static final Logger LOG = LoggerFactory.getLogger(HeaderComponent.class);
private MenuComponent menu = new MenuComponent(getDriver());
public HeaderComponent(NgWebDriver ngdriver) {
super(ngdriver);
}
public MenuComponent getMenuComponent() {
return menu;
}
}
This class is absolutely nothing to do with testNG itself, so how can I initialize everything for the outcome of:
#Inject
MenuComponent menu
Everything I try the menu throws a nullPointerException because I am having trouble having guice somewhat loaded I think.
I have create some general example for you - test with injection example
It works as you're expecting, I hope. It provides some test configs, injects them to driver and at last driver is injected in test component.
Result test looks like:
import com.google.inject.Inject;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
#Guice(modules = {TestModule.class})
public class SimpleTest {
#Inject
ComponentUnderTest component;
#Test
public void sampleTest() {
System.out.println(component.getParamToTest());
System.out.println(component.param);
System.out.println(component.elseone);
}
}

Bean interface and Bean implementation in different projects

Is it possible to have a bean interface in a project and the implementation of that bean in another project that includes the previous project as a dependency?
I have the following interface:
package com.proj1.util;
import .....;
public interface Notification {
addNotification();
addError();
}
In the same project (i.e. Proj1) I have also the following class:
package com.proj1.util.exception;
import .....;
public class ExceptionHandler extends RuntimeException ... {
private String errorMessage;
#Override
public void handle() {
Util.getBeanInstance(Notification.class).addError(errorMessage);
}
}
Now in the second project I have the actual implementation of Notification that is as follows:
package com.proj2.beans;
#Named
#ConversationScoped
public class NotificationBean implements Notification, Serializable {
private static final long serialVersionUID = 1L;
...
}
This situation leads to an exception in Tomcat with the message "WebBeans context with scope type annotation #ConversationScoped does not exist within current thread"
My proposal was to add a Factory that produces my NotificationBean but it doesn't seem to change much.
package com.proj2.beans.cdi;
import javax.enterprise.inject.New;
import javax.enterprise.inject.Produces;
import com.proj1.util.Notification;
public class NotificationBeanFactory {
#Produces
public Notification create(#New NotificationBean notificationBean) {
return notificationBean;
}
}
The question is how can I use a bean in a project in which I have only it's interface while the bean implementation is in another project. Is it possible?
The exception suggests there is no running conversation so I would start by determining when do you attempt to use #ConversationScoped bean and from which class.
Your code pieces indicate that ExceptionHandler class calls a magical formula which we do not know anything else about:
Util.getBeanInstance(Notification.class).add(...);
Trying to use this when there is no active conversation might lead to the exception you see. Therefore you could #Inject ExceptionHandler into NotificationBean so that you only ever use it while there is active conversation.
As for the Weld question regarding interface and impl in different projects; it is possible. in your proj2 Weld will simply identify a bean NotificationBean and amongst it's types there will also be Notification hence you can then #Inject Notification.
It might not work the other way round though - in proj1 you cannot #Inject Notification because proj1 itself does not have any bean which would implement that interface.

Using Resource from different package in Jersey Application

I have developed an SDK that uses a Resource in a rest package:
package com.example.some.package.rest;
...
#Path("/health")
public class HealthResource {
public HealthResource() {
// some code
}
#GET
#Path("/")
#Produces(MediaType.TEXT_HTML)
public Response getHealth() {
// some code to return health
}
}
Then I have another package with an Application implementation:
package com.example.different.package.rest;
...
public class HealthApplication extends Application {
public Set<Object> getSingletons() {
return Sets.<Object> newHashSet(new HealthResource());
}
}
However, this will not work for me. I have to use another wrapper class:
package com.example.different.package.rest;
...
#Path("")
public class WrapperHealthResource extends HealthResource {
public WrapperHealthResource() {
super();
}
}
If I use WrapperHealthResource in the HealthApplication instead of HealthResource, then it works fine.
I think it's pretty useless to have this extra class. How can I get rid of this complexity?
Firstly, I haven't been able to test this on Jersey 1.8 - I only have a 2.7 test harness around. But the API hasn't really changed in this area so you should be OK.
If you only need the Application class to enforce the Singleton of your HealthResource resource and nothing else, then I would just annotate the class with #Singleton and remove your Application class. That's the easiest.
I'm not able to reproduce your issue with 2.7, so this may be an issue with 1.8 (unlikely in this instance) or how you're registering your Application. If you want to post the rest of your code, I might be able to help.
Will
PS - if you're able, upgrade to 2.8.

Categories

Resources