Spring AOP 基于自定义注解实现日志记录

一、写一个自定义注解

注解中包括配置方法所在模块名称,以及功能名称,当然我们在注解里可以自定义。
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
    
	/** 模块 */
    String service() default "";

    /** 功能 */
    String action() default "";

    /** 操作 */
    String option() default "";
    
}

二、建切面类

  切面类里面定义好切点配置,以及所有的需要实现的通知方法。
import java.lang.reflect.Method;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
@Aspect
@Component("logAspect")
public class LogAspect {
 
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
 
    // 配置织入点
    @Pointcut("@annotation(com.test.aspact.Log)")
    public void logPointCut() {
    }
 
    /**
     * 前置通知 用于拦截操作,在方法返回后执行
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
	handleLog(joinPoint, null);
    }
 
    /**
     * 拦截异常操作,有异常时执行
     * 
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e) {
	handleLog(joinPoint, e);
    }
 
    private void handleLog(JoinPoint joinPoint, Exception e) {
	try {
	    // 获得注解
	    Log controllerLog = getAnnotationLog(joinPoint);
	    if (controllerLog == null) {
		return;
	    }
	    // 获得方法名称
	    String className = joinPoint.getTarget().getClass().getName();
	    String methodName = joinPoint.getSignature().getName();
	    String action = controllerLog.action();
	    String title = controllerLog.title();
	    //打印日志,如有需要还可以存入数据库
	    log.info(">>>>>>>>>>>>>模块名称:{}",title);
	    log.info(">>>>>>>>>>>>>操作名称:{}",action);
	    log.info(">>>>>>>>>>>>>类名:{}",className);
	    log.info(">>>>>>>>>>>>>方法名:{}",methodName);
	} catch (Exception exp) {
	    // 记录本地异常日志
	    log.error("==前置通知异常==");
	    log.error("异常信息:{}", exp.getMessage());
	    exp.printStackTrace();
	}
    }
 
    /**
     * 是否存在注解,如果存在就获取
     */
    private static Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();
		if (method != null) {
	   	 return method.getAnnotation(Log.class);
		}
		return null;
    }
}

三、spring.xml配置

    在spring的配置文件中,开启注解的扫描,开启切面扫描。
    <context:component-scan base-package="com.test.**"/>
	
    <mvc:annotation-driven  />
	
    <aop:aspectj-autoproxy />
	   
    <aop:config proxy-target-class="true"></aop:config>

四、测试Controller

@Controller
public class HelloController {
    
    private static final Logger log = LoggerFactory.getLogger(HelloController.class);
    
    @RequestMapping("/hello")
    //对应的自定义注解,当方法上写这个注解时,就会进入切面类中
    @Log(service="哈喽模块",action="say哈喽")
    public String sayHello() {
	log.info("HelloController sayHello:{}","hello world!");
	return "hello";
    }
}

五、切面类注解

    @Aspect  声明切面,修饰切面类,从而获得 通知。

@Before 前置通知,在目标方法开始之前执行

@AfterReturning 后置通知

@Around 环绕 注意:环绕通知内部一定要确保执行proceed()该方法,如果不执行该方法,业务bean中被拦截的方法就不会被执行。当执行该方法,如果后面还有切面的话,它的执行顺序应该是这样的:先执行后面的切面,如果后面没有切面了,再执行最终的目标对象的业务方法。若不执行该方法,则后面的切面,业务bean的方法都不会被执行。
其实我们仅使用环绕通知就可以实现前置通知、后置通知、异常通知、最终通知等的效果。

@AfterThrowing 抛出异常

@After 最终

@PointCut ,切入点,修饰方法 private void xxx(){} 之后通过“方法名”获得切入点引用

上面例子中用到了 @AfterReturning @AfterThrowing,其他的配置方向差异不大,读者可自行配置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Spring AOP来通过自定义注解实现切入点。首先,定义一个自定义注解,并在需要切入的方法上使用该注解,然后定义一个切面,并在切面中使用@Before 或 @Around 注解来拦截被标记的方法,最后,在Spring的配置文件中声明所需的切面,此时,所有被标记的方法都会被拦截。 ### 回答2: 使用Spring AOP切入自定义注解有以下几个步骤: 1. 在项目中引入Spring AOP的依赖,一般为spring-aopspring-aspects。 2. 在配置文件中开启Spring AOP的自动代理功能。可以通过在XML配置文件中添加<aop:aspectj-autoproxy />或在Java配置文件中添加@EnableAspectJAutoProxy注解实现。 3. 创建一个切面类,用于定义切入的逻辑。这个类需要使用@Component或者其他Spring注解进行标识,以便Spring能够扫描到。 4. 在切面类的方法中,使用@Before、@After等注解定义切入点和具体的切入操作。例如,使用@Before注解定义在某个注解标记的方法执行之前切入的逻辑。 5. 在注解中定义自定义的切点。可以使用@Retention和@Target等元注解来配置注解的生命周期和使用范围。 6. 在目标类或方法上添加自定义的注解。例如,在一个Service类的某个方法上添加自定义注解。 7. 运行项目,Spring会根据配置自动代理目标类,当目标类或方法被调用时,切面类中定义的切入逻辑就会自动被执行。 8. 可以通过配置切入的顺序、通知的类型等来进一步细化切入的逻辑。 通过以上步骤,我们可以使用Spring AOP方便地切入自定义注解实现对目标类或方法的增强、日志记录、权限控制等功能。 ### 回答3: 使用Spring AOP切入自定义注解需要以下几个步骤: 1. 定义一个自定义的注解。可以使用Java提供的`@interface`关键字创建一个注解,例如: ```java @Target(ElementType.METHOD) // 定义注解的作用范围为方法 @Retention(RetentionPolicy.RUNTIME) // 注解在运行时可见 public @interface CustomAnnotation { // 自定义注解的属性 } ``` 2. 创建一个切面类来处理注解。可以使用Spring提供的`@Aspect`注解来标记切面类,并在方法上使用`@Before`、`@After`等注解来定义切入点和增强逻辑。例如: ```java @Aspect @Component public class CustomAspect { @Before("@annotation(customAnnotation)") // 拦截带有CustomAnnotation注解的方法 public void beforeMethod(CustomAnnotation customAnnotation) { // 在方法执行前执行的逻辑 } } ``` 3. 配置Spring AOP。在Spring配置文件中添加AOP的配置,例如使用`<aop:aspectj-autoproxy>`标签开启自动代理,并指定切面类的包名,让Spring能够自动扫描并应用切面逻辑。 4. 在目标方法上使用自定义注解。在需要切入的方法上标记使用自定义注解,例如: ```java @CustomAnnotation public void doSomething() { // 方法的实际逻辑 } ``` 这样,在调用`doSomething()`方法时,Spring AOP会拦截到带有`@CustomAnnotation`注解的方法,并执行切面逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值