Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.springframework.boot.jdbc.DataSourceBuilder;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.jdbc.datasource.DataSourceTransactionManager;
- import org.springframework.transaction.PlatformTransactionManager;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
- import org.springframework.transaction.annotation.Transactional;
- import javax.sql.DataSource;
- @Configuration
- @EnableTransactionManagement
- public class TestInnerTxThrowingException {
- public static void main(String[] args) {
- AnnotationConfigApplicationContext applicationContext =
- new AnnotationConfigApplicationContext(TestInnerTxThrowingException.class);
- final FooService fooService = applicationContext.getBean(FooService.class);
- fooService.foo();
- }
- public class FooService {
- private final BarService barService;
- public FooService(BarService barService) {
- this.barService = barService;
- }
- @Transactional
- public void foo() {
- try {
- barService.bar();
- } catch (Exception ex) {
- System.out.println("exception " + ex.getMessage());
- }
- }
- }
- public class BarService {
- @Transactional
- public void bar() {
- throw new RuntimeException("to rollback inner tnx");
- }
- }
- @Bean
- PlatformTransactionManager transactionManager() {
- return new DataSourceTransactionManager(dataSource());
- }
- @Bean
- DataSource dataSource() {
- return DataSourceBuilder
- .create().url("jdbc:h2:mem")
- .username("sa")
- .password("")
- .build();
- }
- @Bean
- BarService barService() {
- return new BarService();
- }
- @Bean
- FooService fooService() {
- return new FooService(barService());
- }
- }
Add Comment
Please, Sign In to add comment