gpt4 book ai didi

java - Spring @ContextConfiguration 中加载位置的顺序

转载 作者:行者123 更新时间:2023-12-01 14:33:51 27 4
gpt4 key购买 nike

我使用以下配置进行数据库集成测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/spring-master.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@Transactional()
public class EmployeeAccessPropertyTest {

spring-master.xml 按以下顺序加载 spring 配置文件:

<import resource="classpath:spring/db/dev-datasource-config.xml"/>
<import resource="classpath:spring/db/jpa-config.xml"/>
<import resource="classpath:spring/db/transaction-config.xml"/>
<import resource="classpath:spring/db/component-config.xml"/>

dev-datasource-config.xml 定义 dataSource 并通过 liquibase 初始化数据库方案:

<context:property-placeholder location="classpath:db/config/dev-data-access.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="liquibase" class="liquibase.integration.spring.SpringLiquibase">
<property name="dataSource" ref="dataSource" />
<property name="changeLog" value="classpath:db/changelog/db.changelog-master.xml" />
<property name="dropFirst" value="true" />
</bean>

现在,当我运行测试时,出现以下错误:

javax.persistence.PersistenceException: [PersistenceUnit: studentPersistenceUnit] Unable to build EntityManagerFactory
...
Caused by: org.hibernate.HibernateException: Missing table: employees

看起来,当entityManagerFactory初始化时(在jpa-config.xml文件中),表没有创建。好的,我首先通过 liquibase maven 插件生成方案:

mvn initialize liquibase:update

通过 Spring 上下文注释以下数据库方案生成:

<!--<bean id="liquibase" class="liquibase.integration.spring.SpringLiquibase">-->
<!--<property name="dataSource" ref="dataSource" />-->
<!--<property name="changeLog" value="classpath:db/changelog/db.changelog-master.xml" />-->
<!--<property name="dropFirst" value="true" />-->
<!--</bean>-->

问题就解决了。我该怎么做才能确保 Spring 首先加载 dev-datasource-config.xml,初始化 liquibase bean,然后才加载 jpa-config.xml,如下所示:

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"/>

最佳答案

使用“depends-on”属性,如 spring 手册中所述:

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-factory-dependson

例如

<bean id="beanOne" class="ExampleBean" depends-on="manager"/>

<bean id="manager" class="ManagerBean" />

关于java - Spring @ContextConfiguration 中加载位置的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16644603/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com