If we want to use the @Transactional
annotation on private methods, we cannot use Spring’s default proxy mode - it only works for public methods that are called from client code.
For self-invoked methods we need to use AspectJ.
An Example
This may be the case e.g. when we want to save incoming data and send a letter using that data within a transaction. If saving the data fails we do not want to send the letter. If sending the letter fails we do not want to loose the data that we received. Hence, we want to save the data in a separate transaction, by annotating our saveData(..) method with @Transactional(propagation = Propagation.REQUIRES_NEW)
.
Configuring Spring To Use AspectJ
On a @Configuration
class we just need to set the AspectJ advice mode for the transaction management configuration:
1 2 3 4 5 6 | |
Configuring Maven To Run The AspectJ Compiler
Next we need to use the AspectJ compiler, so let’s add its needed dependencies:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
The AspectJ compiler itself can then be enabled with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
If we do not use <forceAjcCompile>
and do not set the <weaveDirectory>
AspectJ will not weave the transaction code into our generated Groovy bytecode. Instead, it will warn us with No sources found skipping aspectJ compile when Maven runs. That is as the aspectj-maven-plugin processes the src/main/java directory by default but not src/main/groovy.
How The AspectJ Generated Code Looks Like
Just for completeness, let’s look how AspectJ has wrapped the saveData(..) method with a transaction. Using the Procyon decompiler we can see:
1 2 3 4 | |