我遇到了 Playframwork 已弃用的烦人问题GlobalSettings
问题,我想把我的 conde 移到里面onStart
按照建议的方式,但实际上我无法完成此操作,文档没有任何意义,而且我不知道如何解决这个问题,我花了几天又几天的时间试图做到这一点,但没有运气!
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 protected]") == null) {
String email = "[email protected]";
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
中的方法Global extends GlobalSettings
java 文件,我尝试将其提取到外部模块,但没有成功。
public class GlobalModule extends AbstractModule {
protected void configure() {
initialDB();
}
}
我在 Scala 中找到了一些解决方案,但不知道这在 java 中是如何实现的,但我没有时间学习它,除此之外我也不喜欢它。
您需要两个类 - 一个用于处理初始化,一个模块用于注册绑定。
初始化代码:
@Singleton
public class OnStartup {
@Inject
public OnStartup(final UserService userService) {
if (userService.findUserByEmail("[email protected]") == null) {
String email = "[email protected]";
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"
通过使单例渴望,它将在应用程序启动时运行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)