如何将某些东西注入表格 [英] How to inject something into a form

查看:75
本文介绍了如何将某些东西注入表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从播放2.4.0以来,我们可以使用DI框架.

Since play 2.4.0, we can use a DI framework.

我正在尝试在我的应用中使用DI.我将jpa查找器从模型类上的静态方法移动到了注入到控制器中的服务层中的方法.

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.

我的主要问题是我有一些带有validate方法的表格,在我的validate方法中,我使用了一些查找器.

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

对于登录表单中的示例,我使用"User.authenticate"方法.现在,我已经在UserSvc上将此静态方法替换为新方法,我想将服务注入到Form中,但是它不起作用.

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.

似乎无法向Form中注入某些东西,那么我该如何解决我的问题

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

推荐答案

Play Framework表单不可依赖注入,并且作用域与userService不同,因此您不能通过注释将依赖项注入Login表单.试试这个:

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

这篇关于如何将某些东西注入表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆