AOP注解开发

目录

创建切面类并配置

@Aspect定义为切面类

@Before:前置通知

@AfterReturning:后置通知

@Around:环绕通知

@AfterThrowing:异常通知

@After:最终通知

切入点配置


创建目标类并配置

创建切面类并配置

<!--开启aop注解开发-->
<aop:aspectj-autoproxy/>
<!--配置目标类-->
<bean id="dao" class="com.aop.zhujie.Dao"/>
<!--配置切面类-->
<bean id="aspect" class="com.aop.zhujie.MyAspect"/>

@Aspect定义为切面类

@Aspect
public class MyAspect 

@Before:前置通知

@Before(value = "execution(* com.aop.zhujie.Dao.ff(..))")
public void before(){
    System.out.println("前置增强");
}

@AfterReturning:后置通知

@AfterReturning(value = "execution(* com.aop.zhujie.Dao.hh(..))",returning ="result")
public void after(Object result){
    System.out.println("后置增强"+result);
}

@Around:环绕通知

@Around(value = "execution(* com.aop.zhujie.Dao.huanrao(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("环绕前通知");
    Object proceed = joinPoint.proceed();//加入原本的方法
    System.out.println("环绕后通知");
    return proceed;
}

@AfterThrowing:异常通知

@AfterThrowing(value = "execution(* com.aop.zhujie.Dao.ec(..))",throwing = "throwable")
public void ec(Throwable throwable){
    System.out.println("异常通知"+throwable.getMessage());
}

@After:最终通知

:与后置通知的区别

他们俩都会放到目标方法的后面去执行,但是遇到异常,最终通知任然会执行

@After(value = "execution(* com.aop.zhujie.Dao.ec(..))")
public void zuizhong(){
    System.out.println("最终通知");
}

切入点配置

//切入点注解
@Pointcut(value ="execution(* com.aop.zhujie.Dao.ec(..))")
public void Pointcut1(){};
应用:
@AfterThrowing(value = "MyAspect.Pointcut1()",throwing = "throwable")
public void ec(Throwable throwable){
    System.out.println("异常通知"+throwable.getMessage());
}
@After(value = "MyAspect.Pointcut1()")
public void zuizhong(){
    System.out.println("最终通知");
}
### Java AOP注解开发教程与最佳实践 #### 启用AOP支持 为了在项目中使用面向切面编程(AOP),需要引入`spring-boot-starter-aop`依赖并开启自动代理功能。通过添加`@EnableAspectJAutoProxy`注解到应用程序入口类上可以轻松完成此操作[^1]。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.EnableAspectJAutoProxy; @SpringBootApplication @EnableAspectJAutoProxy public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` #### 创建自定义注解 创建一个简单的自定义注解用于标记哪些方法应该被拦截处理: ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface LogExecutionTime {} ``` #### 编写切面逻辑 编写具体的业务逻辑之前先定义好通用的日志记录方面,这里采用环绕通知的方式,在目标方法执行前后分别打印时间戳信息。 ```java import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Around("@annotation(LogExecutionTime)") public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); try { return joinPoint.proceed(); } finally { long executionTime = System.currentTimeMillis() - start; logger.info("{} executed in {} ms", joinPoint.getSignature(), executionTime); } } } ``` 上述代码实现了当任何带有`LogExecutionTime`标注的方法被执行时都会触发该方面的行为,并输出其运行耗时时长至控制台日志文件中去[^2]。 #### 应用场景实例化 最后一步就是将这些组件组合起来实际运用了。比如下面这个服务接口的具体实现就利用到了前面所提到的技术要点来增强自身的可维护性和扩展能力。 ```java @Service public class UserServiceImpl implements UserService { @Override @LogExecutionTime public User getUserById(Long id){ // ... business logic here ... } } ``` 这样每当调用了`getUserId()`函数之后就会有相应的性能统计信息被捕获下来供后续分析之用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值