我对 Playframwork 弃用 GlobalSettings
问题有恼人的问题,我想将 onStart
中的 conde 移动到建议的方式,但实际上我无法完成此操作,文档毫无意义,我不知道如何解决这个问题,我花了几天又几天的时间试图做到这一点,但没有运气!
https://www.playframework.com/documentation/2.5.x/GlobalSettings
只是我想运行初始数据库方法
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();
}
}
这是 Global extends GlobalSettings
java 文件中的 onStart
方法,我试图将它提取到外部模块,但没有成功。
public class GlobalModule extends AbstractModule {
protected void configure() {
initialDB();
}
}
我在 Scala 中找到了一些解决方案,但不知道这在 java 中如何,但我没有时间学习它,除此之外我也不喜欢它。
最佳答案
您需要两个类 - 一个处理初始化,一个模块注册绑定(bind)。
初始化代码:
@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"
通过使单例成为 eager,它将在应用程序启动时运行。
关于onStart 的 java Playframework GlobalSettings 弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35842293/