簡體   English   中英

java Playframework對於onStart的GlobalSettings棄用

[英]java Playframework GlobalSettings deprecation for onStart

我對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@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中是怎么回事,但我沒有時間去學習它,除此之外我也不喜歡它。

您需要兩個類 - 一個用於處理初始化,另一個用於注冊綁定。

初始化代碼:

@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"

通過使單例急切,它將在應用程序啟動時運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM