Recursion Using AspectJ

I am new to AspectJ and I have a problem that inspires me if some research I cannot fix. I have the following aspect regarding the Bank, the aspect checks whether the Bank's balance is maintained after each public method call.

pointcut BankCheck(Bank bank): call(public * Bank.*(..)) && target(bank); Object around(Bank bank): BankCheck(bank) { int balance = bank.getTotalBalance(); Object result = proceed(bank); if (balance != bank.getTotalBalance()) { LOGGER.warn("The total balance of the bank is not equal."); } else { LOGGER.info("Ok"); } return result; } 

The problem is that in the aspect I use the bank.getTotalBalance () method, which itself is the usual banking method. Therefore, every aspect is recommended every time, and this recursion problem continues until the exception is tailored. Is there a way to fix this, for example, by disabling the Soviet mechanism inside the aspect?

+6
source share
2 answers

Try the following:

 public aspect BankTotalBalanceAspect { pointcut BankCheck(Bank bank): call(public * Bank.*(..)) && target(bank); Object around(Bank bank): BankCheck(bank) && !within(BankTotalBalanceAspect) { int balance = bank.getTotalBalance(); Object result = proceed(bank); if (balance != bank.getTotalBalance()) { LOGGER.warn("The total balance of the bank is not equal."); } else { LOGGER.info("Ok"); } return result; } } 
+4
source

I'm not too familiar with the pointpointJ AspectJ syntax, but is there any way to exclude the getTotalBalance call from the pointcut definition? This will prevent recursion from recurring.

Also, your pointcut definition seems to fit too tightly: I believe that the balance check you implement in your aspect should only be done for writing methods. Thus, a call in readonly mode, such as getTotalBalance , should not match. You have a way to distinguish between readonly and write methods in the target class, e. d. existing transaction annotations or something like that?

If not, you can enter these (custom) annotations yourself and configure your pointcut to match all calls to public methods that are not marked readonly. But this will mean changing the code in the target class, which is not always an option. But YMMV.

0
source

Source: https://habr.com/ru/post/896031/


All Articles