2016-03-07 40 views
3

我有惱人的問題與Playframwork棄用GlobalSettings問題,我想我的內onStart孔德移動到建議的方式,但其實我不能得到這個工作,文檔沒有任何意義,我有不知道如何解決這個問題,我花了幾天和幾天的時間試圖讓它沒有運氣!的Java Playframework GlobalSettings棄用了在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(); 
    } 
} 

我發現在斯卡拉一些解決方案,也不知道這是如何在Java中,但我沒有時間去學習它,旁邊的我不喜歡它。

回答

11

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

的初始化代碼:

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

通過讓單身人員渴望,它會在應用程序啓動時運行。

+0

是的,我嘗試了類似的東西,我到達'OnStartup',但後來我得到'錯誤注入構造函數,java.lang.RuntimeException:沒有啓動應用程序' –

+0

哦,似乎是因爲我訪問'Play.application ).configuration()'來獲得配置。 –

+1

非常感謝你,我終於解決了我的問題:)問題很複雜,我試圖訪問實例不應該在應用程序完成啓動前調用,我在構造函數'public OnStartup(最終UserService userService,最終配置配置)'並像'configuration.getString(「initialName」)那樣訪問配置'' –