Spring自定义注解简单使用四步走

在实际开发中,很多时刻我们会有记录请求日志,定时任务日志等需求,在每个方法中都编写相同的代码去记录日志显然是不合理的。

Spring已经为我们提供了面向切面编程的思想,不妨简单的使用下自定义注解。

简单自定义注解分四步:

1:在配置中打开aop编程

<!-- 自定义AOP -->
    <aop:aspectj-autoproxy proxy-target-class="true">
        <aop:include name="serviceAspect" />
    </aop:aspectj-autoproxy>
    <bean id = "serviceAspect" class="com.thc.tenantcenter.aspect.LogAspect"></bean>

 class指向的是切面解析类下文会有提到

2:编写自己自定义的注解

package com.thc.tenantcenter.aspect;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LogAnnotation {

	String desc() default "打印日志";
}

3:编写自己的切面实现类,就是上文所说的bean指向的路径

package com.thc.tenantcenter.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect //该注解标示该类为切面类 
@Component //注入依赖
public class LogAspect {  
  
    //标注该方法体为后置通知,当目标方法执行成功后执行该方法体  
    @AfterReturning("within(com.thc.tenantcenter..*) && @annotation(rl)")  
    public void addLogSuccess(JoinPoint jp, LogAnnotation rl){  
        Object[] parames = jp.getArgs();//获取目标方法体参数  
        for (int i = 0; i < parames.length; i++) {  
            System.out.println(parames[i]);  
        }  
        System.out.println(jp.getSignature().getName());  
        String className = jp.getTarget().getClass().toString();//获取目标类名  
        System.out.println("className:" + className);
        className = className.substring(className.indexOf("com"));  
        String signature = jp.getSignature().toString();//获取目标方法签名  
        System.out.println("signature:" + signature);
    }  
}

 4:在com.thc.tenantcenter包下及子包下方法上添加自己定义的注解

 

    @LogAnnotation(desc = "通过ID获取实体信息")
    @Override                                                                                              
    public AdminLog getAdminLogById(Integer id) {                                                    
        return adminLogMapper.getAdminLogById(id);                                                   
    }    

 

 

 

  运行结果为:

1
getAdminLogById
className:class com.thc.tenantcenter.biz.adminlog.service.impl.AdminLogServiceImpl
signature:AdminLog com.thc.tenantcenter.biz.adminlog.service.impl.AdminLogServiceImpl.getAdminLogById(Integer)

以上是简单的自定义注解使用,希望能帮助初学者解决问题

 

posted @ 2017-11-08 18:32  红尾巴的猪  阅读(21666)  评论(0编辑  收藏  举报