Java

Java注解(Annotation)- 实例

2020-09-22  本文已影响0人  丿星纟彖彳亍

1、AOP切面

注解

@Documented //记录javadoc
@Target(ElementType.METHOD) //运用到的地方
@Retention(RetentionPolicy.RUNTIME) //注解的生命周期
public @interface LogProcessor {
}

切面

@Aspect
public class LogAspect {

//    @Pointcut("execution(public int com.yt.bean.Cat.eat())")
//    public void pointCut(){
//    }

    @Pointcut("@annotation(com.yt.anno.LogProcessor)")
    public void pointCut(){
    }

    @Before(value = "pointCut()")
    public void logStart(){
        System.out.println("方法之前开始运行:::::");
    }

    @After("pointCut()")
    public void logEnd(){
        System.out.println("方法之后开始运行:::::");
    }

    @AfterReturning("pointCut()")
    public void logRetrun(){
        System.out.println("方法返回时运行::::");
    }

    @AfterThrowing("pointCut()")
    public void logThrow(){
        System.out.println("方法出现异常运行:::");
    }

    @Around("pointCut()")
    public Object logAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("方法环绕增强前::::");
        Object proceed = proceedingJoinPoint.proceed();
        System.out.println("方法环绕增强后::::");
        return proceed;
    }
}

连接点

public class Cat {

    @LogProcessor
    public int eat(int num){
        System.out.println("毛毛要吃饭了。。");
        return num;
    }
}

Spring实体类

@Configuration
@EnableAspectJAutoProxy
public class MainConfig {
     @Bean
     public  Cat cat(){
         return new Cat();
     }

     @Bean
     public LogAspect logAspect(){
         return new LogAspect();
     }
}

测试用例

/**
 * Unit test for simple App.
 */
public class AppTest {
    /**
     * Rigorous Test :-)
     */
    @Test
    public void DemoTest(){
        AnnotationConfigApplicationContext anno = new  AnnotationConfigApplicationContext(MainConfig.class);
        Cat bean = anno.getBean(Cat.class);
        bean.eat(1);
    }
}
//返回结果
/*
方法环绕增强前::::
方法之前开始运行:::::
毛毛要吃饭了。。
方法环绕增强后::::
方法之后开始运行:::::
方法返回时运行::::
*/

2、使用@Valid+BindingResult进行controller参数校验

见:使用@Valid+BindingResult进行controller参数校验

3、在反射中使用示例

/**
 * Annotation在反射函数中的使用示例
 */
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    String[] value() default "unknown";
}

/**
 * Person类。它会使用MyAnnotation注解。
 */
class Person {
    
    /**
     * empty()方法同时被 "@Deprecated" 和 "@MyAnnotation(value={"a","b"})"所标注 
     * (01) @Deprecated,意味着empty()方法,不再被建议使用
     * (02) @MyAnnotation, 意味着empty() 方法对应的MyAnnotation的value值是默认值"unknown"
     */
    @MyAnnotation
    @Deprecated
    public void empty(){
        System.out.println("\nempty");
    }
    
    /**
     * sombody() 被 @MyAnnotation(value={"girl","boy"}) 所标注,
     * @MyAnnotation(value={"girl","boy"}), 意味着MyAnnotation的value值是{"girl","boy"}
     */
    @MyAnnotation(value={"girl","boy"})
    public void somebody(String name, int age){
        System.out.println("\nsomebody: "+name+", "+age);
    }
}

public class AnnotationTest {
    public static void main(String[] args) throws Exception {
        // 新建Person
        Person person = new Person();
        // 获取Person的Class实例
        Class<Person> c = Person.class;
        // 获取 somebody() 方法的Method实例
        Method mSomebody = c.getMethod("somebody", new Class[]{String.class, int.class});
        // 执行该方法
        mSomebody.invoke(person, new Object[]{"lily", 18});
        iteratorAnnotations(mSomebody);
        

        // 获取 somebody() 方法的Method实例
        Method mEmpty = c.getMethod("empty", new Class[]{});
        // 执行该方法
        mEmpty.invoke(person, new Object[]{});        
        iteratorAnnotations(mEmpty);
    }
    
    public static void iteratorAnnotations(Method method) {

        // 判断 somebody() 方法是否包含MyAnnotation注解
        if(method.isAnnotationPresent(MyAnnotation.class)){
            // 获取该方法的MyAnnotation注解实例
            MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
            // 获取 myAnnotation的值,并打印出来
            String[] values = myAnnotation.value();
            for (String str:values)
                System.out.printf(str+", ");
            System.out.println();
        }
        
        // 获取方法上的所有注解,并打印出来
        Annotation[] annotations = method.getAnnotations();
        for(Annotation annotation : annotations){
            System.out.println(annotation);
        }
    }
}

运行结果:

somebody: lily, 18
girl, boy, 
@cn.bcsoft.annotation.MyAnnotation(value=[girl, boy])

empty
unknown, 
@cn.bcsoft.annotation.MyAnnotation(value=[unknown])
@java.lang.Deprecated()
上一篇 下一篇

猜你喜欢

热点阅读