Spring @Transaction method call by the method within the same class, does not work?

前端 未结 8 2218
谎友^
谎友^ 2020-11-22 05:07

I am new to Spring Transaction. Something that I found really odd, probably I did understand this properly.

I wanted to have a transactional around method level and

8条回答
  •  -上瘾入骨i
    2020-11-22 05:31

    The problem here is, that Spring's AOP proxies don't extend but rather wrap your service instance to intercept calls. This has the effect, that any call to "this" from within your service instance is directly invoked on that instance and cannot be intercepted by the wrapping proxy (the proxy is not even aware of any such call). One solutions is already mentioned. Another nifty one would be to simply have Spring inject an instance of the service into the service itself, and call your method on the injected instance, which will be the proxy that handles your transactions. But be aware, that this may have bad side effects too, if your service bean is not a singleton:

    
      
        ...
    
    
    public class UserService {
        private UserService self;
    
        public void setSelf(UserService self) {
            this.self = self;
        }
    
        @Transactional
        public boolean addUser(String userName, String password) {
            try {
            // call DAO layer and adds to database.
            } catch (Throwable e) {
                TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
    
            }
        }
    
        public boolean addUsers(List users) {
            for (User user : users) {
                self.addUser(user.getUserName, user.getPassword);
            }
        } 
    }
    

提交回复
热议问题