我正在尝试使用带有脚本配置的H2嵌入式数据库在测试期间创建和加载数据库。
它工作正常,但当我尝试为我的数据库交互添加事务支持时,我在上下文初始化期间收到错误。
这是我的春季配置:
<bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:mem:embeddedH2Database;MODE=Oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<jdbc:embedded-database id="embeddedH2Database" type="H2">
<jdbc:script location="classpath:db/sql/c`enter code here`reate-db.sql" />
<jdbc:script location="classpath:db/sql/insert-data.sql" />
</jdbc:embedded-database>
<tx:advice id="txAdvice" transaction-manager="txManager">
<!-- the transactional semantics... -->
<tx:attributes>
<tx:method name="*" timeout="60" />
</tx:attributes>
</tx:advice>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dbcpDataSource"/>
</bean>
<aop:config>
<aop:pointcut id="serviceOperation" expression="execution(* x.y.service.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>
</aop:config>
这是bean创建错误:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embeddedH2Database': Cannot create inner bean '(inner bean)#23bff419' of type [org.springframework.jdbc.datasource.init.CompositeDatabasePopulator] while setting bean property 'databasePopulator'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#23bff419': Cannot create inner bean '(inner bean)#1d2bd371' of type [org.springframework.jdbc.datasource.init.ResourceDatabasePopulator] while setting bean property 'populators' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1d2bd371': Cannot create inner bean '(inner bean)#65fe9e33' of type [org.springframework.jdbc.config.SortedResourcesFactoryBean] while setting bean property 'scripts'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#65fe9e33': Post-processing of FactoryBean's object failed; nested exception is java.lang.AssertionError
答案 0 :(得分:0)
由于我正在使用事务,因此它与执行脚本以创建表和加载数据发生冲突。
这些脚本需要在外部执行,而不应用spring config添加的事务语义。
所以我按如下方式更改了嵌入式数据库bean以删除脚本元素:
<jdbc:embedded-database id="embeddedH2Database" type="H2"/>
在我的测试之前添加了@Sql注释来创建表和加载表。
@Sql({"classpath:db/sql/create-db.sql", "classpath:db/sql/insert-data.sql"})