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();
}
}
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();
}
}
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.
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
.
play.modules.enabled += "com.example.modules.OnStartupModule"
By making the singleton eager, it will run when the application is starting up.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.