Spring AOP
June 22, 2020
M02 Q05 How many advice types does Spring support?
How many advice types does Spring support?
Spring supports the following advice types:
@Before
– executed before join point matched by pointcut is executed
@After
– executed after join point matched by pointcut is executed
@AfterThrowing
– executed when an exception is thrown from join point matched by pointcut.Throwing
field informs us that we want to get the original exception.
@AfterReturning
– executed after join point matched by pointcut is executed successfully without any exception.Returning
field says that we want to get the return object.
@Around
– allows you to take full control over join point matched by pointcut, most powerful advice, allows you to implement all advices from above, you need to callProceedingJoinPoint::proceed()
to execute original code and change arguments that are being passed to the original method.
What are they used for?
Some examples of usage for each Advice type:
@Before
- Authorization, Security
- Logging
- Data Validation
@After
- Logging
- Resource Cleanup
@AfterThrowing
- Logging
- Error Handling
@AfterReturning
- Logging
- Data Validation for method result
@Around
- Transactions
- Distributed Call Tracing
- Authorization, Security
Which advices can you use to try and catch exceptions?
To catch exceptions you can use two advices:
@AfterThrowing
with throwing fieldset and exception passed as an argument@Around
with try … catch block implemented