Frage

I am currently writing a typical REST API using Play Framework.
The Play controllers (static methods as you know) call some services.
Services are provided by a ServicesManager.
The code is something like :

class RestController {
    protected static UserService userService;
    protected static void getServices() {
        userService = ServicesManager.getUserService();
    }
}

class UserApiController extends RestController {
    public static Result createUser() {
        getServices();
        ...
        userService.createUser();
        ...
    }
    public static Result updateUser(String userId) {
        getServices();
        ...
        userService.updateUser(...);
        ...
    }
}

Several things bother me in my code :
- getServices() is used in each controller method. How could I avoid it ?
- the design is based on static (due to Play) and protected access. It implies strong coupling. Would you agree (or disagree) this is quite a design flaw ?

Thanks.

War es hilfreich?

Lösung

Depending on which version of Play you are using, there are steps you can take to make your code "less WET" and/or more loosely coupled:

Versions up to and including Play 2.0

Extend play.GlobalSettings (if you are not already doing so), and override the onStart method:

@Override
public void onStart(final Application app) {
    // Initialise your ServicesManager class here
}

Next, I would remove the getServices() method from your parent controller:

public class RestController extends Controller {

    protected static UserService userService = ServicesManager.getUserService();

    // Other service declarations ...
}

This way you don't have to invoke getServices() from each of your action methods.

Play 2.1 onwards

As you've mentioned, in earlier versions of Play controller classes are not instantiated and actions are defined as static methods. Play 2.1 introduced the concept of controller instantiation, and gave developers control over managing controller creation. You can find a reference implementation here of how to tell the Spring framework to manage your controllers and wire in service classes. This now contributes to looser-coupled code.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top