SpringBoot通过注解实现AOP
新手上路,通过这种方式记录一下,有什么不到位的地方还请谅解!
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.定义注解
@Target({ElementType.METHOD}) //可用在方法名上
@Retention(RetentionPolicy.RUNTIME)//运行时有效
public @interface ListenFunction {
}
@Target、@Retention是java中的元注解,
元注解的作用就是负责注解其他注解。Java定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。Java5.0定义的元注解有以下几种:
@Target @Retention @Documented @Inherited
3.定义切面
@Aspect
@Component
@Order(1) //如果有多个 可以定义来控制顺序 数字越小执行顺序靠前
public class ListenFunctionAspect {
@Pointcut("@annotation(com.example.shopping_demo.aspect.ListenFunction)")
//自定义注解的路径
public void pointCut() {
}
@Before("pointCut()")
public void doBefore(){
System.out.println("方法之前运行");
}
@After("pointCut()")
public void doAfter(){
System.out.println("方法之后运行");
}
}
@Aspect:使当前类成为切面类
@Order( ) :给当前切面标序,按照序号来执行多个切面
@Pointcut:定义切入点,这边是对注解切入,也可以对类切入,
如:@Pointcut (“execution(public * com.example.shopping_demo.controller..(…))”)
4.使用注解
@Service
public class test_Server {
@ListenFunction
public void testFunction(){
System.out.println("我是方法");
}
}