EntityManager 不被 Guice 注入

EntityManager don't being injected by Guice

我更新了我的 createInjector 调用以包含我的 JPAPersisteModule...

Guice.createInjector(new ApplicationModule(), new JpaPersistModule("simpleRestApplication"));

在我的服务中,我的 DAO 注入没有问题...

@Path("/users")
public class UserService {

    @Inject
    private UserDAO dao;

    public UserService() {
        Application.getInjector().injectMembers(this);
    }


}

在我的 UserDAOImpl 上,Provider 没有被注入...

@Inject
private Provider<EntityManager> em;

这被打印到控制台上:

1) Error in custom provider, java.lang.NullPointerException while locating com.google.inject.persist.jpa.JpaPersistService while locating javax.persistence.EntityManager

在我的 persistence.xml 上,持久性单元声明如下:

<persistence-unit name="simpleRestApplication">

    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <properties>
        <!-- Configuração do driver -->
        <property name="hibernate.dialect"
            value="org.hibernate.dialect.Oracle10gDialect" />
        <property name="hibernate.connection.driver_class"
            value="oracle.jdbc.driver.OracleDriver" />

        <!-- Configuração de conexão -->
        <property name="hibernate.connection.url"
            value="jdbc:oracle:thin:@localhost:1521/XE" />
        <property name="hibernate.connection.username"
            value="system" />
        <property name="hibernate.connection.password"
            value="myPassword123" />
        <property name="hibernate.connection.autocommit"
            value="true" />

        <!-- Configuração do hibernate -->
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="true" />
        <property name="hibernate.hbm2ddl.auto" value="update" />
        <property name="hibernate.connection.release_mode"
            value="auto" />
        <property name="current_session_context_class"
            value="thread" />
        <property name="hibernate.connection.autoReconnect"
            value="true" />

    </properties>

</persistence-unit>

基于此 link 我更改了 ApplicationModule 上的 configure() 方法以安装 JpaPersistenceModule 并启动 PersistService...

@Singleton
private static class JPAInitializer {
    @Inject
    public JPAInitializer(final PersistService service) {
        service.start();
    }
}

@Override
protected void configure() {

    install(new JpaPersistModule("simpleRestApplication"));
    bind(JPAInitializer.class).asEagerSingleton();

    // another bindings...

}

现在 EntityManager 被注入,没有任何错误...

public class UserDAOImpl implements UserDAO {

    @Inject
    private EntityManager em;

}