How to insert something into a form
With play 2.4.0 we can use the DI structure.
I am trying to use DI in my application. I have moved my jpa finders from static methods to model classes to service layer methods that I inject into my controllers.
My main problem is that I have some forms using the validate method and in my validation method I am using some search engines.
For example, in the login form, I use the "User.authenticate" method. Now that I've replaced this static method with a new one in my UserSvc, I want to inject my service into my form, but it doesn't work.
It seems that it is not possible to insert something into the form as I can solve my problem.
public class MyController {
// Inject here can be used in controller methods but not in the form validate method
@Inject UserSvc userSvc;
public static class Login {
// Inject here is not filled : NPE
@Inject UserSvc userSvc;
public String email;
public String password;
public String validate() {
// How can I use userSvc here ?
}
}
@Transactional(readOnly = true)
public Result authenticate() {
Form<Login> loginForm = form(Login.class).bindFromRequest();
if (loginForm.hasErrors()) {
return badRequest(login.render(loginForm));
} else {
Secured.setUsername(loginForm.get().email);
return redirectConnected();
}
}
}
source to share
Play Framework
forms do not depend on injection and have different scope than userService
, so you cannot inject your dependencies into the login form by annotation. Try the following:
public String validate() {
UserSvc userSvc = Play.application().injector().instanceOf(UserSvc.class);
}
source to share