Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

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 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();
        }
}

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.

like image 732
Al-Mothafar Avatar asked Dec 05 '22 18:12

Al-Mothafar


1 Answers

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 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();
        }
    }
}

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.

like image 98
Steve Chaloner Avatar answered Dec 09 '22 15:12

Steve Chaloner