How to inject something into a form

2019-02-18 13:13发布

Since play 2.4.0, we can use a DI framework.

I am trying to use DI in my app. I moved my jpa finders from static methods on my models classes to methods in a service layer that I inject into my controllers.

My main problem is that I have some forms with a validate method and in my validate methode I use some finders.

For exemple in a login form I use a "User.authenticate" method. Now that I have replaced this static method to a new one on my UserSvc, I want to inject my service into my Form but it does not work.

It seems that it is not possible to inject something into a Form so how can I 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();
        }
    }
}

1条回答
萌系小妹纸
2楼-- · 2019-02-18 13:50

Play Framework forms are not dependency injectable and have different scope than userService, thus you cannot inject your dependencies into Login form by annotation. Try this:

public String validate() {
    UserSvc userSvc = Play.application().injector().instanceOf(UserSvc.class);
}
查看更多
登录 后发表回答