spring 事务, 坑

第一种:实现接口的方法必须是public的,下面的代码编译报错

@Component
public class TestA implements A{
    @Autowired
    StockLogRepository repository;

    @Override
    @Transactional
    void methodA(){
        System.out.println("this is TestA method A");
        Iterable all = repository.findAll();
        System.out.println();
    }

    @Transactional
    public void methodB() {
        System.out.println("this is TestA method B");
        Iterable all = repository.findAll();
        System.out.println();
    }
}

interface A {
    void methodA();

    void methodB();
}

@Component
public class TestB {
    @Autowired
    TestA testA;

    public void methodA() {
        testA.methodA();
        System.out.println();
        testA.methodB();
        System.out.println();
    }
}

 

第二种:

虽然没有使用接口,但是spring aop proxy无法在包外切入时引入事务,事务不生效

@Component
public class TestA{
    @Autowired
    StockLogRepository repository;

    @Transactional
    void methodA(){
        System.out.println("this is TestA method A");
        Iterable all = repository.findAll();
        System.out.println();
    }

    @Transactional
    public void methodB() {
        System.out.println("this is TestA method B");
        Iterable all = repository.findAll();
        System.out.println();
    }
}

@Component
public class TestB {
    @Autowired
    TestA testA;

    public void methodA() {
        testA.methodA();
        System.out.println();
        testA.methodB();
        System.out.println();
    }
}

 

你可能感兴趣的:(spring)