java – 将外部数据插入persistence.xml

我希望我的persistence.xml动态设置它的一些属性,具体如下:

<property name="hibernate.connection.password" value="password"/>
<property name="hibernate.connection.username" value="username"/>

我可以构建一个可以为我提供所需数据的类,但是我不知道如何以这样的方式设置类:

<property name="hibernate.connection.password" value="${my.clazz.pass}"/>
<property name="hibernate.connection.username" value="${my.clazz.user}"/>

我试着像这样设置课程

public class clazz{

  String pass;
  String user;

  public clazz(){
    //do stuff to set pass and user
  }

  //getter/setter
}

但这不起作用.我没有在这里或谷歌找到方法,但我已经多次看到${my.clazz.smth} -way.

那么,我该如何设置呢? 🙂

提前致谢!

最佳答案 所以,前一段时间解决了这个问题,但我仍然没有回答:

Anthony Accioly向我指出了正确的方向:

我将它添加到我的applicationContext.xml的entityManagerFactory中

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitPostProcessors">
        <bean class="my.package.SetupDatabase">
        </bean>
    </property>
    //the other stuff
</bean>

相应的类,在这种情况下我使用hibernate:

package my.package;

public class SetupDatabase implements PersistenceUnitPostProcessor {

    private String username;
    private String password;
    private String dbserver;

    public void SetupDatabase(){
        //do stuff to obtain needed information
    }

    public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
        pui.getProperties().setProperty("hibernate.connection.username", username );
        pui.getProperties().setProperty("hibernate.connection.password", password);
        pui.getProperties().setProperty("hibernate.connection.url", dbserver ); 
    }

}

这样,在启动整个过程时,只需完成一次设置,但所需的数据可能会“外包”.

再次感谢您指出正确的方向!

点赞