java Playframework对于onStart的GlobalSettings弃用 [英] java Playframework GlobalSettings deprecation for onStart

查看:472
本文介绍了java Playframework对于onStart的GlobalSettings弃用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个恼人的问题,Playframwork已弃用 GlobalSettings 问题,我想将我的conde移到 onStart 中以建议的方式,但实际上我不能完成这个,文档没有意义,我不知道如何解决这个问题,我花了几天时间试图让它没有运气!

I have annoying issue with Playframwork deprecated GlobalSettings issue, I want to move my conde inside onStart to suggested way, but Actually I can't get this done, the documentation make no sense, and I have no idea how to solve this, I spent days and days trying to make it with no luck !

https:// www。 playframework.com/documentation/2.5.x/GlobalSettings

我只想运行初始数据库方法

Simply I want to run initial database method

private void initialDB() {
        UserService userService = play.Play.application().injector().instanceOf(UserService.class);
        if (userService.findUserByEmail("email@company.com") == null) {
            String email = "email@company.com";
            String password = "1234";
            String fullName = "My Name";
            User user = new User();
            user.password = BCrypt.hashpw(password, BCrypt.gensalt());
            user.full_name = fullName;
            user.email = email;
            user.save();
        }
}

这是在 onStart 中的方法全局扩展GlobalSettings java文件,我试图将其解压缩到外部模块但没有运气。

This was inside onStart method in Global extends GlobalSettings java file, I tried to extract it to external module but no luck.

public class GlobalModule extends AbstractModule {

    protected void configure() {
        initialDB();
    }
}

我在Scala中找到了一些解决方案,不知道这是怎么回事可以在java中,但我没有时间去学习它,除此之外我也不喜欢它。

I found some solutions in Scala and no idea how this can be in java, but I have no time to learn it, beside that I don't like it too.

推荐答案

你需要两个类 - 一个用于处理初始化,一个用于注册绑定。

You need two classes - one to handle the initialization, and a module to register the binding.

初始化代码:

@Singleton
public class OnStartup {

    @Inject
    public OnStartup(final UserService userService) {
        if (userService.findUserByEmail("email@company.com") == null) {
            String email = "email@company.com";
            String password = "1234";
            String fullName = "My Name";
            User user = new User();
            user.password = BCrypt.hashpw(password, BCrypt.gensalt());
            user.full_name = fullName;
            user.email = email;
            user.save();
        }
    }
}

模块:

public class OnStartupModule extends AbstractModule {
    @Override
    public void configure() {
        bind(OnStartup.class).asEagerSingleton();
    }
}

最后,将模块添加到 application.conf

play.modules.enabled += "com.example.modules.OnStartupModule"

通过使单例急切,它将在应用程序启动时运行。

By making the singleton eager, it will run when the application is starting up.

这篇关于java Playframework对于onStart的GlobalSettings弃用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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