Tuesday, 15 January 2013

How should I design my Play2 java application so that complies with the "Play2 thinking" -



How should I design my Play2 java application so that complies with the "Play2 thinking" -

i'm building play2 application java receive couple of phone numbers , post rest service sends sms.

i have created controller , i'm thinking controller handle request, perform unmarshalling java list. thinking of creating smsservice class handle calling. can't understand how should implement in play2 manner.

do i, in controller, instantiate smsservice typing new? or utilize dependency injection? maybe i'm colored spring background, forget injection , write in controller? maybe create method static , utilize smsservice smsservice.sendsms(numbers)

i have checked samples follow 2.1 folder of play2 examples there not handle case. have missed in documentation.

how , why?

sms controller:

public class sms extends controller { private static final objectmapper mapper = new objectmapper(); @bodyparser.of(value = bodyparser.json.class) public static result invitetoreview() { objectnode result = json.newobject(); jsonnode json = request().body().asjson(); if(json == null) { result.put("status", "ko"); result.put("message", "missing phone number list [phone_numbers]"); homecoming badrequest(result); } list<string> numbers = new arraylist<string>(); typereference collectiontype = new typereference<arraylist<string>>() { }; seek { numbers = mapper.readvalue(json.get("phone_numbers"), collectiontype); } grab (ioexception e) { // handle error } smsservice smsservice = new smsservice(); result = smsservice.sendsms(numbers); homecoming ok(result); } }

since got answers did this.

global:

public class global extends globalsettings { private static final injector injector = createinjector(); /** * need injection. * * @param controllerclass * @param <a> * @return * @throws exception */ @override public <a> getcontrollerinstance(class<a> controllerclass) throws exception { homecoming injector.getinstance(controllerclass); } private static injector createinjector() { homecoming guice.createinjector(); } }

controller:

public class sms extends controller { private static final objectmapper mapper = new objectmapper(); @inject private smsservice smsservice; @bodyparser.of(value = bodyparser.json.class) public result invite(){ objectnode result = json.newobject(); smsservice.sendsms(new arraylist<string>()); result.put("status", "ok"); //cool stuff ehere homecoming ok(result); } }

routes:

get /sms/invite @controllers.sms.invite()

build:

val appdependencies = seq( javacore, "com.google.inject" % "guice" % "3.0", )

java design playframework-2.1

No comments:

Post a Comment