springboot Aop 方法拦截、注解拦截

2017-12-05  本文已影响1152人  _王仔

Action.java

//此注解只能修饰方法
@Target(ElementType.METHOD)
//当前注解如何去保持
@Retention(RetentionPolicy.RUNTIME)
//生成到API文档
@Documented
public @interface Action {
    String name();
}

AopConfig.java

//JAVA配置类
@Configuration
//Bean扫描器
@ComponentScan("com.wangzhi.springboot.aop.test")
//开启spring对aspectJ的支持
@EnableAspectJAutoProxy
public class AopConfig {}

这个类下的方法我们采用注解来拦截

@Service
public class DemoAnnotationService {

    @Action( name = "注解式拦截的add操作")
    public void add() {}
}

这个类下的方法我们采用方法规则来拦截

@Service
public class DemoMethodService {
    public void add() {}
}

LogAspect.java

@Aspect
@Component
public class LogAspect {
    
    //定义切面
    @Pointcut("@annotation(com.wangzhi.springboot.aop.test.Action)")
    public void annotationPointCut() {}
    
    //声明一个advice,并使用@pointCut定义的切点
    @After("annotationPointCut()")
    public void after(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //从切面中获取当前方法
        Method method = signature.getMethod();
        //得到了方,提取出他的注解
        Action action = method.getAnnotation(Action.class);
        //输出
        System.out.println("注解式拦截" + action.name());
    }
    //定义方法拦截的规则
    @Before("execution(* com.wangzhi.springboot.aop.test.DemoMethodService.*(..))")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature =  (MethodSignature) joinPoint.getSignature();
        //拦截了方法
        Method method = signature.getMethod();
        //直接获取方法名字
        System.out.println("方法规则式拦截" + method.getName());
    }
}

启动器

public class Application {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
        DemoMethodService methodService = context.getBean(DemoMethodService.class);
        DemoAnnotationService annotationService = context.getBean(DemoAnnotationService.class);
        
        annotationService.add();
        methodService.add();
        
        context.close();
    }
}

pom.xml依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.12.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.8.10</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.10</version>
    </dependency>
上一篇 下一篇

猜你喜欢

热点阅读