Spring 4 注解新特性

来源:互联网 发布:送餐员下载什么软件 编辑:程序博客网 时间:2024/06/05 03:22

一、注解方面的改进

spring4对注解API和ApplicationContext获取注解Bean做了一点改进。

获取注解的注解,如@Service是被@Compent注解的注解,可以通过如下方式获取@Componet注解实例:

Java代码  收藏代码
  1. Annotation service = AnnotationUtils.findAnnotation(ABService.class, org.springframework.stereotype.Service.class);  
  2. Annotation component = AnnotationUtils.getAnnotation(service, org.springframework.stereotype.Component.class);  

 

获取重复注解:

比如在使用hibernate validation时,我们想在一个方法上加相同的注解多个,需要使用如下方式:

Java代码  收藏代码
  1. @Length.List(  
  2.         value = {  
  3.                 @Length(min = 1, max = 2, groups = A.class),  
  4.                 @Length(min = 3, max = 4, groups = B.class)  
  5.         }  
  6. )  
  7. public void test() {  

可以通过如下方式获取@Length:

Java代码  收藏代码
  1. Method method = ClassUtils.getMethod(AnnotationUtilsTest.class"test");  
  2. Set<Length> set = AnnotationUtils.getRepeatableAnnotation(method, Length.List.class, Length.class);  

 

当然,如果你使用Java8,那么本身就支持重复注解,比如spring的任务调度注解,

Java代码  收藏代码
  1. @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. @Documented  
  4. @Repeatable(Schedules.class)  
  5. public @interface Scheduled {   
Java代码  收藏代码
  1. @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. @Documented  
  4. public @interface Schedules {  
  5.   
  6.     Scheduled[] value();  
  7.   
  8. }  

 

这样的话,我们可以直接同时注解相同的多个注解:

Java代码  收藏代码
  1. @Scheduled(cron = "123")  
  2. @Scheduled(cron = "234")  
  3. public void test     

但是获取的时候还是需要使用如下方式:

Java代码  收藏代码
  1. AnnotationUtils.getRepeatableAnnotation(ClassUtils.getMethod(TimeTest.class"test"), Schedules.class, Scheduled.class)  

 

ApplicationContext和BeanFactory提供了直接通过注解获取Bean的方法:

Java代码  收藏代码
  1. @Test  
  2. public void test() {  
  3.     AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();  
  4.     ctx.register(GenericConfig.class);  
  5.     ctx.refresh();  
  6.   
  7.     Map<String, Object> beans = ctx.getBeansWithAnnotation(org.springframework.stereotype.Service.class);  
  8.     System.out.println(beans);  
  9. }  

这样可以实现一些特殊功能。

 

另外和提供了一个AnnotatedElementUtils用于简化java.lang.reflect.AnnotatedElement的操作,具体请参考其javadoc。   

0 0