Spring 学习六 之 注解开发示例

  • 需要一个Aspect 的类,在类上添加注解 @Aspect
package com.john.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.JoinPoint.StaticPart;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.john.service.LimintConfigService;

@Component
@Aspect
public class LoggerAspect {

    @Pointcut(value ="execution(* com.john.service.LimintConfigService.*(..))")
    public void pointCut() {

    }

    @Before(value = "pointCut()")
    public void beforeAdvice() {
        System.out.println("before advice...");    
    }

    @After(value = "pointCut()")
    public void afterAdvice() {
        System.out.println("after advice...");
    }

    @AfterReturning(value = "pointCut()")
    public void returningAdvice() {
        System.out.println("returning advice...");
    }

    @AfterThrowing(value = "pointCut()")
    public void throwAdvice() {
        System.out.println("throw advice...");
    }

    @Around(value = "pointCut()")
    public void aroundAdvice() {
        System.out.println("around advice...");
    }
}
  • 业务逻辑类,在调用业务方法before()时,LoggerAspect 相应的通知,会切入到before()中,执行通知
@Service
public class LimintConfigService {

    public void before() {
        System.out.println("before()");
    }
}
  • 主配置类,简化了,这里主要测试 AOP 功能,所有简化了很多,一定要开启 aspect 功能,在配置类上面加注解 @EnableAspectJAutoProxy
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = {"com.john"})
public class MainConfig {

}
  • 测试
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
        
        LimintConfigService service = context.getBean(LimintConfigService.class);
        service.after();     
          
        context.close();
    }
  • 执行结果,测试时,本人_屏蔽了 aroundAdvice()_ 通知
    执行结果
    接下来,将详细讲解

猜你喜欢

转载自blog.csdn.net/qq_22925909/article/details/85201414