Does Spring @Transactional attribute work on a private method?

后端 未结 8 2049
耶瑟儿~
耶瑟儿~ 2020-11-22 14:03

If I have a @Transactional -annotation on a private method in a Spring bean, does the annotation have any effect?

If the @Transactional annotation is on

8条回答
  •  心在旅途
    2020-11-22 14:46

    Yes, it is possible to use @Transactional on private methods, but as others have mentioned this won't work out of the box. You need to use AspectJ. It took me some time to figure out how to get it working. I will share my results.

    I chose to use compile-time weaving instead of load-time weaving because I think it's an overall better option. Also, I'm using Java 8 so you may need to adjust some parameters.

    First, add the dependency for aspectjrt.

    
        org.aspectj
        aspectjrt
        1.8.8
    
    

    Then add the AspectJ plugin to do the actual bytecode weaving in Maven (this may not be a minimal example).

    
        org.codehaus.mojo
        aspectj-maven-plugin
        1.8
        
            1.8
            1.8
            1.8
            
                
                    org.springframework
                    spring-aspects
                
            
        
        
            
                
                    compile
                
            
        
    
    

    Finally add this to your config class

    @EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
    

    Now you should be able to use @Transactional on private methods.

    One caveat to this approach: You will need to configure your IDE to be aware of AspectJ otherwise if you run the app via Eclipse for example it may not work. Make sure you test against a direct Maven build as a sanity check.

提交回复
热议问题