一. 情景
项目组开发一个数学计数器(加减乘除的计算器)
要求:
- 执行加减乘除运算
- 日志:在程序执行期间追踪正在发生的活动
- 验证:希望计算器只能处理正数的运算
注意: 本项目着重实现日志功能(用AOP实现,后面会详细讲到)
二. 思路
在运算的前后加日志记录,即进行日志功能。
ArithmeticCalculator.java
package com.atguigu.spring.aop.before;
/**
* 算数计算器
* @author user
*
*/
public interface ArithmeticCalculator {
/**
* 加法
* @param i
* @param j
* @return
*/
public int add(int i, int j);
/**
* 减法
* @param i
* @param j
* @return
*/
public int sub(int i, int j);
/**
* 乘法
* @param i
* @param j
* @return
*/
public int mul(int i, int j);
/**
* 除法
* @param i
* @param j
* @return
*/
public int div(int i, int j);
}
ArithmeticCalculatorImpl.java
package com.atguigu.spring.aop.before;
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
@Override
public int add(int i, int j) {
// TODO Auto-generated method stub
//日志记录
System.out.println("The method add begin with [" + i + "," + j + "]");
int result = i + j;
//日志记录
System.out.println("The method add end with result : " + result);
return result;
}
@Override
public int sub(int i, int j) {
// TODO Auto-generated method stub
//日志记录
System.out.println("The method sub begin with [" + i + "," + j + "]");
int result = i - j;
//日志记录
System.out.println("The method sub end with result : " + result);
return result;
}
@Override
public int mul(int i, int j) {
// TODO Auto-generated method stub
//日志记录
System.out.println("The method mul begin with [" + i + "," + j + "]");
int result = i * j;
//日志记录
System.out.println("The method mul end with result : " + result);
return result;
}
@Override
public int div(int i, int j) {
// TODO Auto-generated method stub
//日志记录
System.out.println("The method div begin with [" + i + "," + j + "]");
int result = i / j;
//日志记录
System.out.println("The method div end with result : " + result);
return result;
}
}
Main.java
package com.atguigu.spring.aop.before;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArithmeticCalculator ac = new ArithmeticCalculatorImpl();
int result = ac.add(1, 1);
System.out.println("Main==>:" + result);
}
}
存在的问题: 代码分散,维护难,代价高。
希望:
- 核心业务只包含核心代码
- 日志功能单独定义。以一些手段动态地将日志功能作用到核心业务上
技术点: 动态代理