spring框架详解(五)--AOP注解形式

来源:互联网 发布:java单例模式使用场景 编辑:程序博客网 时间:2024/05/21 15:07

一.前言

   前面讲了AOP的xml形式,这里说明下其注解形式,我们在启动tomCat服务器的时候,大家都会发现从这里面可以看到记载的红色日志信息如下图,那么我们如何自己定义日志呢,直接从案例中说明.

二.AOP案例

   定义一个记载加减乘除的日志状态
     
准备工作:
1.新建一个xml文件拿来包扫描,自动注入
通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。
<context:component-scan base-package="com.eduask.chp.yunsuan"></context:component-scan><aop:aspectj-autoproxy></aop:aspectj-autoproxy>
2,除了spring之前的一些必须jar包外,下面日志log类需要commons-logging的jar包

1.定义运算接口类
public interface Arithmetic {public abstract double add(double a, double b);public abstract double jian(double a, double b);public abstract double cheng(double a, double b);public abstract double chu(double a, double b);}

2.定义其实现类
@Componentpublic class ArithmeticImp implements  Arithmetic{public double add(double a,double b){double result=a+b;return result;}public double jian(double a,double b){double result=a-b;return result;}public double cheng(double a,double b){double result=a*b;return result;}public double chu(double a,double b){double result=a/b;return result;}}

3.aop切面日志通知类 
@Component@Aspectpublic class Logs {private Log log=LogFactory.getLog(this.getClass());//创建一个日志对象@Before("execution(* *.*(..))")//定义切点开始通知public void before(JoinPoint joinPoint ){log.info("The method"+joinPoint.getSignature().getName()+"()begin with "+Arrays.toString(joinPoint.getArgs()));}//获取方法与参数@AfterReturning(pointcut="execution(* *.*(..))",returning="result")//返回结果的通知public void after(JoinPoint joinPoint,Object result ){log.info("The method"+joinPoint.getSignature().getName()+"()end with "+result);}}//返回结果与参数

4.测试
public class Test {public static void main(String[] args) {ApplicationContext app=new ClassPathXmlApplicationContext("applicationcontext.xml");Arithmetic a=(Arithmetic) app.getBean("arithmeticImp");a.add(1, 2);}}

测试结果
    
补充一点:
根据不同的性质,日志信息通常被分成不同的级别,从低到高依次是:“调试( DEBUG )”“信息( INFO )”“警告( WARN )”“错误(ERROR )”“致命错误( FATAL )”。