任何人都可以帮我找出以下异常的解决方案,我想我只是不太了解事务传播机制,这阻碍了我理解下面显示的异常消息的真实含义,所以请帮助我了解整件事,非常感谢你!
java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client).
at org.springframework.batch.core.repository.support.AbstractJobRepositoryFactoryBean$1.invoke(AbstractJobRepositoryFactoryBean.java:164)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy15.createJobExecution(Unknown Source)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:111)
at TestJob.testExcelParserTasklet(TestJob.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.MethodInvocationHelper$1.runTestMethod(MethodInvocationHelper.java:169)
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.run(AbstractTestNGSpringContextTests.java:158)
以下是产生上述异常的代码:
public class TestJob extends BaseTest {
@Test
public void testExcelParserTasklet() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, NoSuchJobException {
Job job = jobRegistry.getJob("parseExcelJob");
jobLauncher.run(job, new JobParameters());
}
}
这是BaseTest:
@ContextConfiguration("classpath:application-context.xml")
public abstract class BaseTest extends AbstractTransactionalTestNGSpringContextTests
{
@Autowired
protected JobRegistry jobRegistry;
@Autowired
protected JobLauncher jobLauncher;
}
答案 0 :(得分:8)
AbstractTransactionalTestNGSpringContextTests将所有测试方法包装在事务中。 Spring批处理作业存储库不喜欢与其他人共享其事务管理器。 逻辑很简单,如果您在步骤失败时与步骤事务管理器共享作业事务管理器,它将回滚步骤和写入作业存储库的数据。这意味着您不会保留数据以重新启动作业。 所以使用Transactional Unit测试很棘手。
查看Spring Batch文档的4.3.1. Transaction Configuration for the JobRepository部分。
我们也有这个问题,所以在找到解决方案之前我们会避免交易测试。 多重交易管理器的使用可能有效,但我还没有尝试过,但看到How to configure mutliple transaction managers with Spring + DBUnit + JUnit