自定义LogUtils类实现AOP

实现AOP织入,需要导入一个AspectJ的开发包 

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.5</version>
    </dependency>

导入AOP约束

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">

实现类:

UserServiceImpl:

public class UserServiceImpl implements UserService{
 
    public void add() {
        System.out.println("增加了一个用户");
    }
 
    public void delete() {
        System.out.println("删除了一个用户");
    }
 
    public void update() {
        System.out.println("更新了一个用户");
    }
 
    public void query() {
        System.out.println("查询了一个用户");
    }
}

LogUtils:


public class LogUtils {

    public void logStart(){
        System.out.println(joinPoint.getSignature().getName()+"方法开始执行");
    }

    public void logException(JoinPoint joinPoint, Exception e){
        System.out.println("方法"+joinPoint.getSignature().getName()+"出现异常,异常为");
    }

    public void logReturn(JoinPoint joinPoint, Object result) {
        System.out.println("[" + joinPoint.getSignature().getName() + "]方法执行完成,结果是[" + result + "]");
    }

    public  void logEnd(JoinPoint joinPoint) {
        System.out.println(joinPoint.getSignature().getName() + "方法执行结束");
    }

    public  void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前");
        //执行方法
        pjp.proceed();

        System.out.println("环绕后");

    }

}

XML配置文件:

 <bean id="userService" class="hjy.service.UserServiceImpl"/>
 <bean id="logUtils" class="hjy.log.LogUtils"/>


<aop:config>
    <aop:aspect ref="logUtils">
        <!-- 切点-->
        <aop:pointcut id="point" expression="execution(* hjy.service.UserServiceImpl.*(..))"/>

        <aop:before method="logStart" pointcut-ref="point"/>
        <aop:around method="around" pointcut-ref="point"/>
        <aop:after method="logEnd" pointcut-ref="point"/>

    </aop:aspect>
</aop:config>

输出结果:

add方法开始执行
环绕前
增加了一个用户
环绕后
add方法执行结束

●@Before:前置通知,在方法执行之前执行
●@After:后置通知,在方法执行之后执行
●@AfterRunning: 返回通知,在方法返回结果之后执行
●@AfterThrowing: 异常通知,在方法抛出异常之后
●@Around:环绕通知,围绕着方法执行
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值