Playframework Guice启动数据库查询

Playframework Guice启动数据库查询,playframework,playframework-2.0,guice,Playframework,Playframework 2.0,Guice,我需要在play framework启动时执行数据库查询以检索服务器信息。我写了一个ServerInstanceModule ie public class ServerInstanceModule extends AbstractModule { ServerInstance serverInstance; @Override protected void configure() { } @Provides @Inject ServerInstance provideServerInst

我需要在play framework启动时执行数据库查询以检索服务器信息。我写了一个ServerInstanceModule ie

public class ServerInstanceModule extends AbstractModule {
ServerInstance serverInstance;

@Override
protected void configure() {

}

@Provides
@Inject
ServerInstance provideServerInstance(Configuration configuration){
    if (serverInstance == null) {
        String serverInstanceId = configuration.getString("instance.db.id");
        try {
            if (serverInstanceId != null) {
                serverInstance = models.managemend.ServerInstance.find.byId(Long.parseLong(serverInstanceId));
            }
        } catch (Throwable e) {
            Logger.error(e.getMessage(), e);
        }
    }
    return serverInstance;
}}
这样做对吗?我试着编写一个服务,声明它为singleton,并急切地加载它

@Singleton public class ServerInstanceService {
@Inject
private Configuration configuration;

ServerInstance serverInstance;

public ServerInstance get() {
    if (serverInstance == null) {
        String serverInstanceId = configuration.getString("instance.db.id");
        try {
            if (serverInstanceId != null) {
                serverInstance = ServerInstance.find.byId(Long.parseLong(serverInstanceId));
            }
        } catch (Throwable e) {
            Logger.error(e.getMessage(), e);
        }
    }
    return serverInstance;
}}

但有时guice会以错误开始,因为serverinstance为null。有人对我如何解决这个问题有什么建议吗?我真的希望使用服务而不是模块。

您面临竞争条件和线程安全问题。这是实现它的最简单的方法,但是
serverInstance
不是线程安全的,因为它可能有变种

@Singleton
public class ServerInstanceService implements IServerInstanceService {

    private final ServerInstance servcerInstance;

    @Inject
    public ServerInstanceService(Configuration config) {
        Long id = // ..
        servcerInstance = ServerInstance.findById(id);
    }

}

然后我会有一个getServerInstance()方法吗?是的,您可以随意对示例代码进行任何附加。非常感谢,我看到您的解决方案比我以前做的更好