spring aop切面入门

 

 

Java 注解

 

 

第一个表示覆盖了父类的方法

第二个表示方法已经过期(但是还是可以使用,会出现警告)

第三表示使用过期方法忽略警告

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Aop

 

需求 如某些方法需要管理员权限才能运行。

  1. 在只能管理员运行的方法里面进行硬编码判断当前用户是不是管理员(侵入式高)
  2. 使用aop进行切面拦截特定的方法(侵入式低)

 

定义切面  在定义adminOnly注解的方法之前进行拦截然后运行方法之前@before插入代码

 

 

package com.Springboot.myBoot.zujie;

import java.lang.annotation.Documented;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

import javax.lang.model.element.Element;

import javax.persistence.Inheritance;

import org.hibernate.validator.internal.xml.ElementType;

import org.mockito.Incubating;

@Target({java.lang.annotation.ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

@Inheritance

@Documented

public @interface Desciption {

String value();  //可以不加

}

 

 

 

定义注解

 

package com.Springboot.myBoot.zujie;

import org.aspectj.lang.annotation.After;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Before;

import org.aspectj.lang.annotation.Pointcut;

import org.springframework.stereotype.Component;

@Aspect

@Component

public class qiemian {

/*@Component  @component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>*/

@Pointcut("@annotation(Desciption)")

public void zdy(){

}

@Before("zdy()")

public void Front(){

System.out.println("我在特定的方法之前运行");

}

@After("zdy()")

public void behind(){

System.out.println("我在特定的方法之前运行");

}

}

 

@RequestMapping("/qiemian")

@Desciption("zdy")

public String zdy(){

     System.out.println("我是一个切面方法  我加了自定义注解");

     return "success";

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

一个参数 long类型

 

 

多个参数 long类型开头

 

 

两个参数 long类型开头和String

 

 

 

 

类级别的需要将注解的范围修改。Type

 

 

 

问号部分可以省略

 

 

 

 

        

 

获取参数

 

 

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/jiahaoJAVA/p/8994605.html