spring配置中的persistence.xml的回退

时间:2014-07-09 22:03:26

标签: xml spring jpa persistence

我的配置如下:

    <bean
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        id="entityManagerFactory">
        <property name="dataSource" ref="dataSource" />

        <property name="persistenceXmlLocation"
            value="classpath:META-INF/spring/environments/${env}/persistence.xml" />
    </bean>

我想要的是,如果

  

META-INF /弹簧/环境/ $ {ENV} /persistence.xml

找不到

,我想要加载LocalContainerEntityManagerFactoryBean

  

META-INF /弹簧/环境的/ dev / persistence.xml中

有可能吗?

1 个答案:

答案 0 :(得分:0)

我认为不是开箱即用。但你可以使用一个小型支持类来完成它。

public class ResourceCandidateResolver {

    @Autowired 
    private ResourceLoader resourceLoader;
    private String[] candidates;

    public String resolve() {
        for (String candidate : candidates) {
            Resource res = resourceLoader.getResource(candidate);
            if (res.exists())
                return candidate;
        }

        return null;
    }

    public String[] getCandidates() {
        return candidates;
    }

    public void setCandidates(String[] candidates) {
        this.candidates = candidates;
    }
}

并使用spel注入它。

<bean id="resourceCandidateResolver" class="beans.ResourceCandidateResolver">
        <property name="candidates">
            <list>
                <value>classpath:/persistence-one.xml</value>
                <value>classpath:/persistence-two.xml</value>
            </list>
        </property>
</bean>
<bean
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    id="entityManagerFactory">
    <property name="dataSource" ref="dataSource" />

    <property name="persistenceXmlLocation"
        value="#{resourceCandidateResolver.resolve()}" />
</bean>

其他选项是Configuration类。