首先是自定义注解类
@Target注解中ElementType.METHOD是指注解在方法上使用ElementType.TYPE是类上
package com.zbc.springbootstudy.config.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author BoChao Zheng
* @Date 2023/3/22 20:11
* @PackageName:com.zbc.springbootstudy.config.Annotation
* @ClassName: MyAdmin
* @Description: TODO
* @Version 1.0
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAdmin {
String dbName() default "";
}
其次就是定义他切面类;编写before,After注解下的方法
当中有方式一和方式二;可以直接使用方式二
@Before(“@within(myadmin)”)//类前执行
这个@within注解是类前执行加的
@within注解有个小坑;如果想放在mapper层面上,注意不能和mybatisPlus搭配使用,因为使用的mp自带的方法,根本不会进去mapper接口层,所以也进不了Before
@Before(“@annotation(myadmin)”)//方法前执行
这个@annotation注解是方法前执行加的
package com.zbc.springbootstudy.config.Annotation;
import com.zbc.springbootstudy.config.DataSourceConfig.DataSourceUtil;
import com.zbc.springbootstudy.service.CupService;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* @Author BoChao Zheng
* @Date 2023/3/22 20:15
* @PackageName:com.zbc.springbootstudy.config.Annotation
* @ClassName: CheckUserAspect
* @Description: TODO
* @Version 1.0
*/
@Component
@Aspect //切面
public class CheckAspect {
@Autowired
private CupService cupService;
// 方式一 old
/*@Pointcut("@annotation(com.zbc.springbootstudy.config.Annotation.MyAdmin)")//切入点
public void checkAdmin(){
}
@Before("checkAdmin()")//方法前执行
public void check(){
DataSourceUtil.setDB("db2");
}
@After("@annotation(myadmin)")//方法前执行
public void checkAfter(MyAdmin myadmin){
System.out.println("方法执行后执行了");
DataSourceUtil.clearDB();
}*/
//方式二
@Before("@annotation(myadmin)")//方法前执行
public void check(MyAdmin myadmin){//对象是注解 属性名要和上面@annotation里的值保持一致
System.out.println("方法前执行");
System.out.println(myadmin.dbName());
DataSourceUtil.setDB(myadmin.dbName());
}
@After("@annotation(myadmin)")//方法前执行
public void checkAfter(MyAdmin myadmin){
System.out.println("方法执行后执行了");
DataSourceUtil.clearDB();
}
@Before("@within(myadmin)")//方法前执行
public void clazzBefore(MyAdmin myadmin){
System.out.println("类执行前执行");
DataSourceUtil.setDB(myadmin.dbName());
}
//拦截类的
@After("@within(myadmin)")//方法前执行
public void clazzAfter(MyAdmin myadmin){
System.out.println("类执行后执行");
DataSourceUtil.clearDB();
}
}