I am trying to learn SpringAOP with AspectJ, by building a small bank transaction simulation. But I am unable to add advice (@Before, @After, @AfterThrowing) to the methods of the aspect class itself.
This is the model
Bank.java
@Component
public class Bank {
private int balance;
private int pinCode;
private int tempPin;
public int getBalance() {
return balance;
}
@Value("10000")
public void setBalance(int balance) {
this.balance = balance;
}
public int getPinCode() {
return pinCode;
}
@Value("6789")
public void setPinCode(int pinCode) {
this.pinCode = pinCode;
}
public int getTempPin() {
return tempPin;
}
public void setTempPin(int tempPin) {
this.tempPin = tempPin;
}
public void withDraw(int amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Successful Withdraw");
} else {
System.out.println("Insufficient Balance");
}
}
}
This is the aspect class
BankAspect.java
@Component
@Aspect
public class BankAspect {
private Bank bank;
public Bank getBank() {
return bank;
}
@Autowired
public void setBank(Bank bank) {
this.bank = bank;
}
@Before("execution(public void dev.ritam.model.Bank.withDraw(..))")
public void validatePin() {
if (bank.getPinCode() != bank.getTempPin()) {
throw new RuntimeException();
}
}
@AfterThrowing("execution(public void dev.ritam.aspect.BankAspect.validatePin(..))")
public void logException() {
System.out.println("Wrong Pin");
}
}
This is the configuration class
AppConfig.java
@Configuration
@EnableAspectJAutoProxy
@ComponentScan("dev.ritam")
public class AppConfig {
@Bean
Bank bank() {
return new Bank();
}
@Bean
BankAspect bankAspect() {
return new BankAspect();
}
}
This is the main method
App.java
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Bank bank = context.getBean(Bank.class);
try {
bank.setTempPin(1234);
bank.withDraw(1000000);
} catch (Exception ignore) {
}
}
}
Only validatePin() @Before advice is getting executed. I am suppose to get 'Wrong Pin' as output, but the @AfterThrowing advice is not being recognized.