Hello Spring Team!
I have a problem:
In my project, I need use @TransactionalEventListener
to handle the Cached-Objects to synchronization,in my demo project, I found a problem: If your need use @Transaction
in TestCase method, you need to auto-rollback the testing data! so you must be use@Transaction
, but now, @TransactionalEventListener
it's not work! OMG! I think so is a bug?
WHY CANNOT USE @Transactional
TO TESTING @TransactionalEventListener
?
Is this a reasonable situation?
Show my demo code:
DemoServiceImpl.java
@Service
public class DemoServiceImpl implements DemoService {
final ApplicationEventPublisher applicationEventPublisher;
public DemoServiceImpl(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
@Transactional
@Override
public void test() throws SQLException {
applicationEventPublisher.publishEvent("Demo Test!");
applicationEventPublisher.publishEvent(Integer.MAX_VALUE);
throw new SQLException("Test exception");
}
}
DemoEventReceiverComponentImpl.java
@Service
//@Component
public class DemoEventReceiverComponentImpl implements DemoEventReceiverComponent {
// @EventListener
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = false)
public void onEvent(String data) {
System.out.println(data);
}
// @EventListener
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = false)
public void onEvent2(Integer data) {
System.out.println(data);
}
}
DemoServiceImplTest.java
@SpringBootTest
class DemoServiceImplTest {
@Autowired
DemoService demoService;
@Transactional // Look at this!!! If you comment this line, onEvent*() it's to work!
@Test
void test1() throws SQLException {
demoService.test();
}
}
[Crying] It took me two days to find out the problem. It was too confusing. I cant say why not? Is there any other solution?
Comment From: rocbin
The root cause of this problem is: @Transactional
in TestCase it to be rollback transaction! onEvent*() is can't calling exection.
Why not improve it so that it can be tested normally.
Comment From: sbrannen
Thanks for getting in touch, but it feels like this is a question that would be better suited to Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use the issue tracker only for bugs and enhancements. Feel free to update this issue with a link to the re-posted question (so that other people can find it) or add some more details if you feel this is a genuine bug.
In fact, I once answered a related question on Stack Overflow that you might find helpful: https://stackoverflow.com/a/36555712/388980
Comment From: rocbin
Thankyou for answer! really.