2016-03-07 45 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”)那样访问配置'' –