简体   繁体   中英

How to change a value in XML programmatically

I have a spring batch application. The database that is used to store meta-data of spring batch job is configured like the following:

In application-context.xml:

<!-- stored job-meta in database - H2 -->
    <bean id="jobRepository"
        class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
        <property name="dataSource" ref="dataSourceMetaData" />
        <property name="transactionManager" ref="transactionManager" />
        <property name="databaseType" value="h2" />    
    </bean>

In database.xml:

<!-- configure H2 database connection -->
<bean id="dataSourceMetaData"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:~/metaDataProd" />
</bean>

Now the application can run in the same environment in multiple instance for ex: one instance for prod & one instance for test. So I have to make the value="jdbc:h2:~/metaDataProd configurable so that both instance does not access the same db.

I can easily do that if I generate the value from a config file. But I am wondering if there is any automatic way of doing this. For example: When an application instance is initiated then a datevalue is appended programmatic ally like this value="jdbc:h2:~/metaData2Jul value="jdbc:h2:~/metaData4Jul

You can use PropertySourcesPlaceholderConfigurer and init the value from various sources, like environment variable, external property file or alike. Then use ${propname} placeholder instead of hardcoded value.

See also related question .

If you don't need to distinguish instances but just want them to be different, there is very simple method with SpEL . Any of the following may do the work:

<property name="url" value="#{ 'jdbc:h2:~/metaData' + T(java.lang.System).nanoTime() }" />

or

<property name="url" value="#{ 'jdbc:h2:~/metaData-' + T(java.util.UUID).randomUUID() }" />

or

<property name="url" value="#{ 'jdbc:h2:~/metaData-' + (new java.text.SimpleDateFormat('ddmm_hh_mm_ss')).format(new java.util.Date()) }" />

If you don't have any control over spring.xml or application but can execute some script before launch, you can generate name in a script and replace jdbc url value in xml (depending on scripting language, there are endless solutions here on SO).

You can specify a JNDI property for that and load that property at init uisng initialContext() method, some like this:

new InitialContext(environment).lookup(myServiceJndiName);

And you can specify different jndi values for different environment in this case test env or production env.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM