[英]java Playframework GlobalSettings deprecation for 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 ! 我对Playframwork弃用的
GlobalSettings
问题有一个恼人的问题,我想把我的conde在onStart
移动到建议的方式,但实际上我不能完成这个,文档没有意义,我不知道如何解决这个问题,我花了几天和几天试图让它没有运气!
https://www.playframework.com/documentation/2.5.x/GlobalSettings 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();
}
}
This was inside onStart
method in Global extends GlobalSettings
java file, I tried to extract it to external module but no luck. 这是在
Global extends GlobalSettings
java文件中的onStart
方法里面,我试图将它提取到外部模块但没有运气。
public class GlobalModule extends AbstractModule {
protected void configure() {
initialDB();
}
}
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. 我在Scala中找到了一些解决方案,不知道这在java中是怎么回事,但我没有时间去学习它,除此之外我也不喜欢它。
You need two classes - one to handle the initialization, and a module to register the binding. 您需要两个类 - 一个用于处理初始化,另一个用于注册绑定。
The initialization code: 初始化代码:
@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();
}
}
}
The module: 模块:
public class OnStartupModule extends AbstractModule {
@Override
public void configure() {
bind(OnStartup.class).asEagerSingleton();
}
}
Finally, add your module to application.conf
. 最后,将您的模块添加到
application.conf
。
play.modules.enabled += "com.example.modules.OnStartupModule"
By making the singleton eager, it will run when the application is starting up. 通过使单例急切,它将在应用程序启动时运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.