将外部数据插入persistence.xml [英] Insert external data into persistence.xml

查看:27
本文介绍了将外部数据插入persistence.xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want my persistence.xml to set some of its properties dynamically, to be specific:

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

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

I can build a class that could provide me the data I need, but I don't know how to set the class up in a way that it works like this:

<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.

But that does not work. I haven't found a way here or in google, but I have seen the ${my.clazz.smth}-way several times.

那么,我该如何设置?:)

So, how can I set that up? :)

提前致谢!

推荐答案

所以,前阵子解决了这个问题,但我还是没有回答:

So, resolved this a while ago, but I still didn't answer:

Anthony Accioly 为我指明了正确的方向:

Anthony Accioly pointed me to the right direction:

我将此添加到我的 applicationContext.xml 的 entityManagerFactory

I added this to my applicationContext.xml's 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:

The corresponding class, in this case I use 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 ); 
    }

}

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

This way the setup is done just once when starting the whole thing up, but the required data may be 'outsourced'.

再次感谢您为我指明了正确的方向!

Thanks again for pointing me to the right direction!

这篇关于将外部数据插入persistence.xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆