Spring AOP实现方式

方式一:调用spring api实现

1.编写UserService接口

public interface UserService {
    void add();
    void delete();
    void update();
    void query();
}

2.实现UserService接口

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("查询方法。。。");
    }
}

3.在方法前添加日志

public class Log implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"类的"+method.getName()+"方法被执行");
    }
}

4.在方法后添加日志

public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object re
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AOP实现方式有两种:基于XML配置和基于注解配置。 1. 基于XML配置 在XML配置文件中,我们可以使用<aop:config>元素来定义AOP配置。该元素包含一个或多个<aop:aspect>元素,每个<aop:aspect>元素定义一个切面。在<aop:aspect>元素内部,我们可以使用<aop:pointcut>元素定义切点,使用<aop:advisor>元素定义通知。 举个例子,我们可以定义一个切面用于日志记录,在XML配置文件中如下: ```xml <aop:config> <aop:aspect id="logAspect" ref="loggingAspect"> <aop:pointcut id="loggingPointcut" expression="execution(* com.example.*.*(..))"/> <aop:advisor advice-ref="loggingAdvice" pointcut-ref="loggingPointcut"/> </aop:aspect> </aop:config> ``` 2. 基于注解配置 在基于注解配置中,我们可以使用@Aspect注解定义切面,使用@Before、@After、@Around等注解定义通知,使用@Pointcut注解定义切点。 举个例子,我们可以定义一个切面用于日志记录,在Java代码中如下: ```java @Aspect @Component public class LoggingAspect { @Pointcut("execution(* com.example.*.*(..))") private void loggingPointcut() {} @Before("loggingPointcut()") public void logBefore(JoinPoint joinPoint) { System.out.println("Method " + joinPoint.getSignature().getName() + " is about to be executed."); } @After("loggingPointcut()") public void logAfter(JoinPoint joinPoint) { System.out.println("Method " + joinPoint.getSignature().getName() + " has been executed."); } } ``` 注意:我们需要在Spring配置文件中启用基于注解的AOP,如下所示: ```xml <aop:aspectj-autoproxy/> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值