简体   繁体   中英

Evaluate properties in Spring's context.xml (basic templating)

I'm wondering whether it is possible to evaluate properties in Spring's xml configuration files. I'm currently already injecting properties using a PropertyPlaceholderConfigurer . But what I want to achieve is to inject a value, if a certain property is true , and inject another value, if it is false .

For example I want to set the hibernate property hibernate.hbm2ddl.auto in my persistence.context.xml to validate only, if my custom property com.github.dpeger.jpa.validate is true . I know I can specify defaults like this:

<property name="jpaProperties">
    <map>
        <entry key="hibernate.hbm2ddl.auto" value="${com.github.dpeger.jpa.validate:none}" />
        ...
    </map>
</property>

But is there a possibility to somehow evaluate a properties' value maybe like this:

<property name="jpaProperties">
    <map>
        <entry key="hibernate.hbm2ddl.auto" value="${com.github.dpeger.jpa.validate?validate:none}" />
        ...
    </map>
</property>

First option:

You can use #{} EL expression and insert ${} placeholder right into this expression:

<property name="jpaProperties">
    <map>
        <entry key="hibernate.hbm2ddl.auto" 
            value="#{${com.github.dpeger.jpa.validate}?'validate':'none'}" />
        ...
    </map>
</property>

Second option:

You can create separate property bean (note, that you have to define xmlns:util namespace and spring-util.xsd location):

<beans ...
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="...
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">


    <util:properties id="props" location="classpath:appliction.properties"/>

    ...

</beans>

Now you can use this property bean in the EL expression by id:

<property name="jpaProperties">
    <map>
        <entry key="hibernate.hbm2ddl.auto" 
            value="#{props['com.github.dpeger.jpa.validate']?'validate':'none'}" />
        ...
    </map>
</property>

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