Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between static controller and non static controller in play framework with Java

I was wondering if there was any significant advantage, or disadvantage, when using non-static controllers in a Java Play!Framework 2.2.x app.

I normally use the clasic static controllers that seem to be the default pattern for Play!.

But whenever I use Guice I obviously need to change that so that I can inject various services. For those wondering how this is done (you add an '@' in front of the function "path" in the routes file):

GET /api/something/someofthat   controllers.MyController.myStaticAction

GET /api/something/someother    @controllers.MyController.myNonStaticAction

public class MyController extends Controller {

    public static Result myStaticAction(){
        return ok("This is not a method.");
    }

    public Result myNonStaticAction(){
        return ok("This is not a static method.");
    }

}

Apart from the obvious and well documented advantage of dependency injection using Guice, it would seem to me that purely non static controllers would help in implementing thread-safe code. But I must say I am not sure of that. So my question is: Can someone point me to cases in which NON-static controllers are recommended? And also cases where static controllers are called for?

Also does it have any effect on the "scala wrapping" that play framework do on the controller functions?

Thanks a lot.

like image 881
le-doude Avatar asked Oct 21 '22 12:10

le-doude


1 Answers

The dependency injection you mentioned is, to me, the reason why non-static controllers should always be used. It makes your code way easier to test.

It is true that non-static controllers can make it slightly easier to write thread-safe code. If you want to put mutable (and not shared across instances) state directly in your controller (which I do not recommend) it helps, however, the controller is only one part of your application, if you have non thread-safe code somewhere else it won't save you.

Can't think of any reason why you would want to use static controllers.

like image 113
vptheron Avatar answered Oct 23 '22 03:10

vptheron