spring aop 日志 注解

前提:接上篇:spring aop 日志

一:无新增依赖包

二:修改切面类(aop.Log4jHandlerAOP.java)

三:修改applicationContext.xml

  1:扫描注入容器新增aop(base-package="dao,service,aop")

  2:支持AOP注解(<aop:aspectj-autoproxy/>)

  3:去除传统AOP的配置以及切面类的注入

 

ps:

  1:applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"   
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:aop="http://www.springframework.org/schema/aop"   
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <context:annotation-config />
    <!-- 根据注解扫描类放入容器  -->
    <context:component-scan base-package="dao,service,aop" />
    <!--升级: 注解,自动注入 -->
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
    <!-- apo 注解 -->
    <aop:aspectj-autoproxy/> 
</beans>

  2:Log4jHandlerAOP.java

package aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import entity.Student;

@Component
@Aspect
public class Log4jHandlerAOP {
    Logger logger = Logger.getLogger(Log4jHandlerAOP.class);;
    
    public Log4jHandlerAOP() {
        super();
        logger.info("创建bean:"+ this.getClass().getName());
    }

    @Pointcut("execution(* service.*.*(..))")  
     private void anyMethod(){}//定义一个切入点
    
    @Before("anyMethod() && args(student)")  
    public void doAccessCheck(Student student){  
        logger.info(student.toString());  
        logger.info("前置通知");  
    }  
      
    @AfterReturning("anyMethod()")  
    public void doAfter(){  
        logger.info("后置通知");  
    }  
      
    @After("anyMethod()")  
    public void after(){  
        logger.info("最终通知");  
    }  
      
    @AfterThrowing("anyMethod()")  
    public void doAfterThrow(){  
        logger.info("例外通知");  
    }  
      
    @Around("anyMethod()")  
    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{  
        logger.info("进入环绕通知");  
        Object object = pjp.proceed();//执行该方法  
        logger.info("退出方法");  
        return object;  
    }
}

 

posted on 2015-04-03 17:43  豪1817  阅读(201)  评论(0编辑  收藏  举报

导航