Spring 4 注解新特性
来源:互联网 发布:送餐员下载什么软件 编辑:程序博客网 时间:2024/06/05 03:22
一、注解方面的改进
spring4对注解API和ApplicationContext获取注解Bean做了一点改进。
获取注解的注解,如@Service是被@Compent注解的注解,可以通过如下方式获取@Componet注解实例:
- Annotation service = AnnotationUtils.findAnnotation(ABService.class, org.springframework.stereotype.Service.class);
- Annotation component = AnnotationUtils.getAnnotation(service, org.springframework.stereotype.Component.class);
获取重复注解:
比如在使用hibernate validation时,我们想在一个方法上加相同的注解多个,需要使用如下方式:
- @Length.List(
- value = {
- @Length(min = 1, max = 2, groups = A.class),
- @Length(min = 3, max = 4, groups = B.class)
- }
- )
- public void test() {
可以通过如下方式获取@Length:
- Method method = ClassUtils.getMethod(AnnotationUtilsTest.class, "test");
- Set<Length> set = AnnotationUtils.getRepeatableAnnotation(method, Length.List.class, Length.class);
当然,如果你使用Java8,那么本身就支持重复注解,比如spring的任务调度注解,
- @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Repeatable(Schedules.class)
- public @interface Scheduled {
- @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface Schedules {
- Scheduled[] value();
- }
这样的话,我们可以直接同时注解相同的多个注解:
- @Scheduled(cron = "123")
- @Scheduled(cron = "234")
- public void test
但是获取的时候还是需要使用如下方式:
- AnnotationUtils.getRepeatableAnnotation(ClassUtils.getMethod(TimeTest.class, "test"), Schedules.class, Scheduled.class)
ApplicationContext和BeanFactory提供了直接通过注解获取Bean的方法:
- @Test
- public void test() {
- AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
- ctx.register(GenericConfig.class);
- ctx.refresh();
- Map<String, Object> beans = ctx.getBeansWithAnnotation(org.springframework.stereotype.Service.class);
- System.out.println(beans);
- }
这样可以实现一些特殊功能。
另外和提供了一个AnnotatedElementUtils用于简化java.lang.reflect.AnnotatedElement的操作,具体请参考其javadoc。
0 0
- Spring 4 注解新特性
- Java新特性1 -- 注解
- jdk 1.5新特性---注解
- java 1.5 新特性-注解
- JDK1.5新特性-注解
- [Java5新特性]Annotation注解
- Spring 3.0 新特性
- Spring 新特性
- Spring 4.1新特性
- Spring 2.5的新特性:配置简化和基于注解的功能
- Spring MVC 3.1新特性 生产者、消费者请求限定 ——注解式控制器详解
- 第六章 注解式控制器详解--Spring MVC 3.1新特性 生产者、消费者请求限定
- jdk1.5新特性(二)_注解
- Annotation注解(1.5新特性)
- java1.5新特性-----》注解----Annotation
- 黑马程序员-jdk1.5新特性--注解
- JDK5新特性---注解学习笔记(一)
- JAVA1.5新特性----注解Annotation
- chrome livestyle插件
- 189. Rotate Array \ 169. Majority Element \ Best time to buy
- PRank算法python实现
- 清除浮动的几种方法
- 隐藏文字
- Spring 4 注解新特性
- git笔记 常规使用
- android音量键调节听筒音量的大小
- 定时器、Date
- FIS
- 为什么不喜欢用360浏览器开发
- 关于C#中get和set
- nginx 使用
- ZCMU-1610- 大四上之横扫千军