文章目录
AOP注解方式
使用步骤
1,使用注解@Component 定义切点类,类似于xml文件中的bean标签
代码示例
package com.lanou3g.spring.simple.say;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
//此处使用了slf4j日志配置
@Slf4j
public class SayHelloImpl implements ISayHello {
@Override
public void sayHello() {
log.info("hello world!");
}
@Override
public void sayHello(String name) {
log.info("hello, " + name);
}
}
2,使用@Ascept和@Component定义一个切面类,其中@Component同切点类的作用相同,@Aspect表示声明该类为切面类
package com.lanou3g.spring.simple.say;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* 定义一个切面,负责收集方法调用的入参、出参(返回值)
*/
@Slf4j
@Aspect // 表示该类是一个切面
@Component // Aspect切面首先必须也是一个普通的bean
public class MethodInOutAspect {
// 指定该方法是一个环绕通知,通知注解的参数代表引用一个切入点表达式
@Around("com.lanou3g.spring.GlobalPointcut.say_all_method()")
public Object aroundM(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取连接点方法的名称
String methodName = joinPoint.getSignature().getName();
// 获取连接点方法的参数
Object[] args = joinPoint.getArgs();
log.debug("[aroundM] "+methodName+"("+ Arrays.toString(args) +") 开始执行");
Object retuVal = joinPoint.proceed();
log.debug("[aroundM] "+methodName+"("+ Arrays.toString(args) +") 返回值: " + retuVal);
return retuVal;
}
@AfterReturning(pointcut = "com.lanou3g.spring.GlobalPointcut.say_all_method()", returning = "ret")
public Object afterRM(Object ret) {
log.debug("[afterRM] 返回值: " + ret);
return ret;
}
}
3,创建注解方式的入口类
需要用的注解:
@Configuration,此注解相当于xml配置中的beans标签
@EnableAspectJAutoProxy,此注解用于开启所有的注解配置、
package com.lanou3g.spring; import com.lanou3g.spring.simple.say.ISayHello; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; /** * 纯注解方式入口类 */ @Slf4j @Configuration @ComponentScan(basePackages = "com.lanou3g.spring.simple.say") @EnableAspectJAutoProxy //开启对AOP相关注解的处理 public class AppByAnnotation { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppByAnnotation.class); ISayHello hello = ctx.getBean(ISayHello.class); hello.sayHello("JinSaiSai"); } }