我试图用guice / dropwizard配置hibernatebundle,需要帮助。我除了dropwizard lib之外,还使用hubspot / dropwizard-guice / 0.7.0 3rd party库。
下面的代码显然无法正常工作,需要帮助找出它。我该如何重写它,以便将hibernatebundle以及最终的会话工厂自动注入到需要它的任何bean中。
MyApplication.java
public class MyApplication extends Application<MyAppConfiguration> { private final HibernateBundle<MyAppConfiguration> hibernateBundle = new HibernateBundle<MyAppConfiguration>(MyModel.class) { @Override public DataSourceFactory getDataSourceFactory(MyAppConfiguration configuration) { return configuration.getDataSourceFactory(); } }; @Override public void initialize(Bootstrap<MyAppConfiguration> bootstrap) { bootstrap.addBundle(hibernateBundle); // ??? bootstrap.addBundle( GuiceBundle.<MyAppConfiguration>newBuilder() .addModule(new MyAppModule()) .enableAutoConfig(getClass().getPackage().getName()) .setConfigClass(MyAppConfiguration.class) .build() ); } }
MyAppModule.java
public class MyAppModule extends AbstractModule { @Provides public SessionFactory provideSessionFactory(MyAppConfiguration configuration) { // really wrong as it creates new instance everytime. return configuration.getHibernateBundle().getSessionFactory(); // ??? } }
MyAppConfiguration.java
public class MyAppConfiguration extends Configuration { @Valid @NotNull private DataSourceFactory database = new DataSourceFactory(); @JsonProperty("database") public DataSourceFactory getDataSourceFactory() { return database; } @JsonProperty("database") public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { this.database = dataSourceFactory; } // ??? public HibernateBundle<MyAppConfiguration> getHibernateBundle() { return new HibernateBundle<MyAppConfiguration>(MyModel.class) { @Override public DataSourceFactory getDataSourceFactory(MyAppConfiguration configuration) { return database; } }; } }
这就是我最终要做的事情。我从这里或邮件列表中都没有得到答案,因此我会认为这种骇人听闻的方法,可能不是正确的方法,但对我有用。
在我的模块中(扩展了abstractmodule):
private final HibernateBundle<MyConfiguration> hibernateBundle = new HibernateBundle<MyConfiguration>(MyModel.class) { @Override public DataSourceFactory getDataSourceFactory(MyConfiguration configuration) { return configuration.getDataSourceFactory(); } }; @Provides public SessionFactory provideSessionFactory(MyConfiguration configuration, Environment environment) { SessionFactory sf = hibernateBundle.getSessionFactory(); if (sf == null) { try { hibernateBundle.run(configuration, environment); } catch (Exception e) { logger.error("Unable to run hibernatebundle"); } } return hibernateBundle.getSessionFactory(); }
修订:
public SessionFactory provideSessionFactory(MyConfiguration configuration, Environment environment) { SessionFactory sf = hibernateBundle.getSessionFactory(); if (sf == null) { try { hibernateBundle.run(configuration, environment); return hibernateBundle.getSessionFactory(); } catch (Exception e) { logger.error("Unable to run hibernatebundle"); } } else { return sf; } }