How to inject something into a form

雨燕双飞 提交于 2019-12-19 09:27:08

问题


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:


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);
}


来源:https://stackoverflow.com/questions/30577431/how-to-inject-something-into-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!