秒懂!使用切面和自定义注解

注解代码:

package  com.test.aop.service
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Document
public @interface LogPrint{
    //可附加属性
    public String desc();//注意属性后面有括号
}

定义了一个方法级别的注解,在运行时有效。

@Target 说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、

类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声

明中使用了target可更加明晰其修饰的目标。

@Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译

在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(这里并不影响class

的执行,因为Annotataion与class使用上是被分离的)。使用这个meta-Annotation可以对Annotation的“生命周期”进行限制。例

如我们常见的@Override,它的@Retention就在source(源代码)阶段,因为这只是针对方法覆盖进行语法检查,在runtime

(运行阶段)就不需要了。

@Document描述其他类型的annotation应该被作为被标注的程序成员的公告API,因此可以被例如javadoc这类的工具文档化。

这是一个标记注解,无成员

/另外还有一个@Inherited 允许子类继承父类的注解,也是一个标注注解,与@Document两者应需求用一个即可。@Inherited阐

//述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被

//用于该class的子类。

切面代码:

package  com.test.aop.util
@Aspect
@Component
public class LogPrintAspect{    
    //自定义切点位置    
    //把切面连接点放在我们注解上    
    @Pointcut("@annotation(com.test.aop.service.LogPrint)")
    private void controllerAspect(){}    
    //自定义前置切面    
    //访问controller方法前先执行的方法    
    @Before("controllerAspect()")    
    public void printLog(){        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.ms");   
        System.out.println(sdf.format(new Date())+" || ");    
    }
}

需获取注解属性的代码:

package  com.test.aop.util
@Aspect
@Component
public class LogPrintAspect{    
    //自定义切点位置    
    //把切面连接点放在我们注解上    
    @Pointcut("@annotation(com.test.aop.service.LogPrint)")
    private void controllerAspect(){}    
    //自定义前置切面    
    //访问controller方法前先执行的方法    
    @Before(value = "controllerAspect()&&@annotation(logPrint)", argNames = "logPrint")    
    public void printLog(LogPrint logPrint){        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.ms");
        System.out.println(sdf.format(new Date())+" || "+ logPrint.desc());    
    }
}

使用:

@LogPrint
@RequsetMapping(value = "/toIndex" method = RequestMethod.GET)
public ModelAndView toIndex(){
    ModelAndView mav = new ModelAndView();
    mav.setViewName("index");
    return(mav);
}



带属性的:

@LogPrint(desc = "属性描述")
@RequsetMapping(value = "/toIndex" method = RequestMethod.GET)
public ModelAndView toIndex(){
    ModelAndView mav = new ModelAndView();
    mav.setViewName("index");
    return(mav);
}

猜你喜欢

转载自blog.csdn.net/huofuman960209/article/details/82223787