spring Aop(1)--注解使用

二话不说直接开始上例子

<dependency>
    <groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

1.定义UserA类,也就是业务类

2.创建Aspect

@Aspect
@Component
public class UserAspects {

    @Pointcut("execution(* com.example.demo.service.*.*(..))")
    public void userAspects(){}

    @Before("userAspects()")
    public void before(JoinPoint joinPoint){
        System.out.println("=====before:"+joinPoint.getTarget().getClass()+":"+joinPoint.getSignature().getName());

    }
  /*  @Around("userAspects()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("=====aroundBefore:"+pjp.getSignature().getName());
        try {
            pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("=====aroundAfter:"+pjp.getSignature().getName());
        return pjp.proceed();
    }*/
    @After("userAspects()")
    public void after(JoinPoint joinPoint){
        System.out.println("=====after:"+joinPoint.getTarget().getClass()+":"+joinPoint.getSignature().getName());
    }
    @AfterReturning("userAspects()")
    public void afterReturning(JoinPoint joinPoint){
        System.out.println("=====afterReturning:"+joinPoint.getTarget().getClass()+":"+joinPoint.getSignature().getName());
    }
}

 @Pointcut("execution(* com.example.demo.service.*.*(..))")为切点

1)execution(* *(..))  
//表示匹配所有方法  
2)execution(public * com. example.service.UserService.*(..))  
//表示匹配com.example.server.UserService中所有的公有方法  
3)execution(* com.example.server..*.*(..))  
//表示匹配com.example.server包及其子包下的所有方法

@Before调用方法前执行

@After代用方法后执行

@AfterReturning方法return后执行

@Around包含before和after

 @AfterThrowing异常抛错后执行

 这里需要注意一下@Component需要带上,这样spring在扫描的时候就会当成一个bean扫描到该类,然后再判断其是否是@Aspect

3.执行业务

@SpringBootApplication
public class DemoApplication {
  public static void main(String[] args) {
    ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
    Object userA = run.getBeanFactory().getBean(UserA.class);
    ((UserA) userA).function();
    

  }
}

4.执行结果

注意:springboot项目是不需要加@EnableAspectJAutoProxy该注解的,因为自动装配过程中默认情况下就已经加上了该注解了,当然你加上也不影响

ok简单的一个AOP切面我们就已经完成了,那spring是怎么实现AOP的呢?下一章我们就这个问题进行讨论

posted @ 2020-04-09 08:56  menco  阅读(10)  评论(0)    收藏  举报