JavaEE——Spring学习笔记03【AOP开发】( 五 )


5.2.3 目标类
/*** 账户类:被切面类*/@Componentpublic class Account {int money = 1000;//取钱/*public void out(){money -=100;//取出100System.out.println("已扣除100元!");}*/public int out() {money -= 100;//取出100System.out.println("已扣除100元!");//int num = 100/0;//设置异常return money;}//存钱public void in() {money += 100;//存储100System.out.println("已存储100元!");}//转账public void transfer() {System.out.println("转账人民币!");}//开户public void open() {System.out.println("开通账户!");}//销户public void close() {System.out.println("账户销户!");}}
5.2.4 切面类
/*** 账户类的切面:其实就是Account业务增强的类*/@Component@Aspectpublic class AccountAspect {/*** 验证账户的合法性:前置通知1*/@Before("execution(public int com.suke.pojo.Account.out())")public void validAuth() {System.out.println("验证账户是否合法!");}/*** 检查余额是否足够:前置通知2*/@Before("execution(public int com.suke.pojo.Account.out())")public void validMoney() {System.out.println("检查余额是否充足!");}/*** 生成对账单*/@AfterReturning("execution(public int com.suke.pojo.Account.out())")public void generateStatement() {System.out.println("生成对账单!");}/*** 发送短信*/@AfterReturning("execution(public int com.suke.pojo.Account.out())")public void sendMsg() {System.out.println("发送短信!");}/*** 后置通知:取完钱后查看余额的方法*///@AfterReturning(value = "http://www.kingceram.com/post/execution(public int com.suke.pojo.Account.out())",returning = "result")@AfterReturning(value = "http://www.kingceram.com/post/accountPoint()", returning = "result")public void getYuMoney(Object result) {System.out.println("账户余额还有:" + result);}/*** 利用环绕通知检查余额是否足够(前置)和生成对账单(后置)*/@Around("execution(public int com.suke.pojo.Account.out())")public Object vaildMoneyAndGenerateStatement(ProceedingJoinPoint ponint) throws Throwable {Object obj = null;//前置通知:检查余额是否充足validMoney();obj = ponint.proceed(); //调用切点的方法//后置通知:生成对账单generateStatement();return obj;}/*** 异常通知*///@AfterThrowing(value = "http://www.kingceram.com/post/execution(public int com.suke.pojo.Account.out())", throwing = "e")@AfterThrowing(value = "http://www.kingceram.com/post/accountPoint()", throwing = "e")public void exception(Exception e) {System.out.println("目标方法执行出错!" + e.getMessage());}/*** 最终的通知*///@After("execution(public int com.suke.pojo.Account.out())")@After(value = "http://www.kingceram.com/post/accountPoint()")public void after() {System.out.println("不管有无异常我都进行通知!");}/*** 配置一个切点*/@Pointcut(value = "http://www.kingceram.com/post/execution(public int com.suke.pojo.Account.out())")public void accountPoint() {}}
5.2.4 测试类
/*** 测试账户的类*/public class AccountTest {@Testpublic void testAccount(){//1、创建Spring的容器对象ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-aop.xml");//2、获取容器中Account对象Account account = (Account) applicationContext.getBean("account");//取钱account.out();}}