Spring中的注解大概可以分为两大类:

1)spring的bean容器相关的注解,或者说bean工厂相关的注解;

2)springmvc相关的注解。

spring的bean容器相关的注解,先后有:@Required, @Autowired, @PostConstruct, @PreDestory,还有Spring3.0开始支持的JSR-330标准javax.inject.*中的注解(@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton).

springmvc相关的注解有:@Controller, @RequestMapping, @RequestParam, @ResponseBody等等。

要理解Spring中的注解,先要理解Java中的注解。

1. Java中的注解

Java中1.5中开始引入注解,我们最熟悉的应该是:@Override, 它的定义如下:

  1. /**
  2. * Indicates that a method declaration is intended to override a
  3. * method declaration in a supertype. If a method is annotated with
  4. * this annotation type compilers are required to generate an error
  5. * message unless at least one of the following conditions hold:
  6. * The method does override or implement a method declared in a
  7. * supertype.
  8. * The method has a signature that is override-equivalent to that of
  9. * any public method declared in Object.
  10. *
  11. * @author Peter von der Ahé
  12. * @author Joshua Bloch
  13. * @jls 9.6.1.4 @Override
  14. * @since 1.5
  15. */
  16. @Target(ElementType.METHOD)
  17. @Retention(RetentionPolicy.SOURCE)
  18. public @interface Override {
  19. }

从注释,我们可以看出,@Override的作用是,提示编译器,使用了@Override注解的方法必须override父类或者java.lang.Object中的一个同名方法。我们看到@Override的定义中使用到了 @Target, @Retention,它们就是所谓的“元注解”——就是定义注解的注解,或者说注解注解的注解(晕了...)。我们看下@Retention

  1. /**
  2. * Indicates how long annotations with the annotated type are to
  3. * be retained. If no Retention annotation is present on
  4. * an annotation type declaration, the retention policy defaults to
  5. * RetentionPolicy.CLASS.
  6. */
  7. @Documented
  8. @Retention(RetentionPolicy.RUNTIME)
  9. @Target(ElementType.ANNOTATION_TYPE)
  10. public @interface Retention {
  11. /**
  12. * Returns the retention policy.
  13. * @return the retention policy
  14. */
  15. RetentionPolicy value();
  16. }

@Retention用于提示注解被保留多长时间,有三种取值:

  1. public enum RetentionPolicy {
  2. /**
  3. * Annotations are to be discarded by the compiler.
  4. */
  5. SOURCE,
  6. /**
  7. * Annotations are to be recorded in the class file by the compiler
  8. * but need not be retained by the VM at run time. This is the default
  9. * behavior.
  10. */
  11. CLASS,
  12. /**
  13. * Annotations are to be recorded in the class file by the compiler and
  14. * retained by the VM at run time, so they may be read reflectively.
  15. *
  16. * @see java.lang.reflect.AnnotatedElement
  17. */
  18. RUNTIME
  19. }
  1. RetentionPolicy.SOURCE 保留在源码级别,被编译器抛弃(@Override就是此类); RetentionPolicy.CLASS被编译器保留在编译后的类文件级别,但是被虚拟机丢弃;
  1. RetentionPolicy.RUNTIME保留至运行时,可以被反射读取。

再看 @Target:

  1. package java.lang.annotation;
  2.  
  3. /**
  4. * Indicates the contexts in which an annotation type is applicable. The
  5. * declaration contexts and type contexts in which an annotation type may be
  6. * applicable are specified in JLS 9.6.4.1, and denoted in source code by enum
  7. * constants of java.lang.annotation.ElementType
  8. * @since 1.5
  9. * @jls 9.6.4.1 @Target
  10. * @jls 9.7.4 Where Annotations May Appear
  11. */
  12. @Documented
  13. @Retention(RetentionPolicy.RUNTIME)
  14. @Target(ElementType.ANNOTATION_TYPE)
  15. public @interface Target {
  16. /**
  17. * Returns an array of the kinds of elements an annotation type
  18. * can be applied to.
  19. * @return an array of the kinds of elements an annotation type
  20. * can be applied to
  21. */
  22. ElementType[] value();
  23. }

@Target用于提示该注解使用的地方,取值有:

  1. public enum ElementType {
  2. /** Class, interface (including annotation type), or enum declaration */
  3. TYPE,
  4. /** Field declaration (includes enum constants) */
  5. FIELD,
  6. /** Method declaration */
  7. METHOD,
  8. /** Formal parameter declaration */
  9. PARAMETER,
  10. /** Constructor declaration */
  11. CONSTRUCTOR,
  12. /** Local variable declaration */
  13. LOCAL_VARIABLE,
  14. /** Annotation type declaration */
  15. ANNOTATION_TYPE,
  16. /** Package declaration */
  17. PACKAGE,
  18. /**
  19. * Type parameter declaration
  20. * @since 1.8
  21. */
  22. TYPE_PARAMETER,
  23. /**
  24. * Use of a type
  25. * @since 1.8
  26. */
  27. TYPE_USE
  28. }

分别表示该注解可以被使用的地方:1)类,接口,注解,enum; 2)属性域;3)方法;4)参数;5)构造函数;6)局部变量;7)注解类型;8)包

所以:

  1. @Target(ElementType.METHOD)
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface Override {
  4. }

表示 @Override 只能使用在方法上,保留在源码级别,被编译器处理,然后抛弃掉。

还有一个经常使用的元注解 @Documented

  1. /**
  2. * Indicates that annotations with a type are to be documented by javadoc
  3. * and similar tools by default. This type should be used to annotate the
  4. * declarations of types whose annotations affect the use of annotated
  5. * elements by their clients. If a type declaration is annotated with
  6. * Documented, its annotations become part of the public API
  7. * of the annotated elements.
  8. */
  9. @Documented
  10. @Retention(RetentionPolicy.RUNTIME)
  11. @Target(ElementType.ANNOTATION_TYPE)
  12. public @interface Documented {
  13. }

表示注解是否能被 javadoc 处理并保留在文档中。

2. 使用 元注解 来自定义注解 和 处理自定义注解

有了元注解,那么我就可以使用它来自定义我们需要的注解。结合自定义注解和AOP或者过滤器,是一种十分强大的武器。比如可以使用注解来实现权限的细粒度的控制——在类或者方法上使用权限注解,然后在AOP或者过滤器中进行拦截处理。下面是一个关于登录的权限的注解的实现:

  1. /**
  2. * 不需要登录注解
  3. */
  4. @Target({ ElementType.METHOD, ElementType.TYPE })
  5. @Retention(RetentionPolicy.RUNTIME)
  6. @Documented
  7. public @interface NoLogin {
  8. }

我们自定义了一个注解 @NoLogin, 可以被用于 方法 和 类 上,注解一直保留到运行期,可以被反射读取到。该注解的含义是:被 @NoLogin 注解的类或者方法,即使用户没有登录,也是可以访问的。下面就是对注解进行处理了:

  1. /**
  2. * 检查登录拦截器
  3. * 如不需要检查登录可在方法或者controller上加上@NoLogin
  4. */
  5. public class CheckLoginInterceptor implements HandlerInterceptor {
  6. private static final Logger logger = Logger.getLogger(CheckLoginInterceptor.class);
  7.  
  8. @Override
  9. public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
  10. Object handler) throws Exception {
  11. if (!(handler instanceof HandlerMethod)) {
  12. logger.warn("当前操作handler不为HandlerMethod=" + handler.getClass().getName() + ",req="
  13. + request.getQueryString());
  14. return true;
  15. }
  16. HandlerMethod handlerMethod = (HandlerMethod) handler;
  17. String methodName = handlerMethod.getMethod().getName();
  18. // 判断是否需要检查登录
  19. NoLogin noLogin = handlerMethod.getMethod().getAnnotation(NoLogin.class);
  20. if (null != noLogin) {
  21. if (logger.isDebugEnabled()) {
  22. logger.debug("当前操作methodName=" + methodName + "不需要检查登录情况");
  23. }
  24. return true;
  25. }
  26. noLogin = handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoLogin.class);
  27. if (null != noLogin) {
  28. if (logger.isDebugEnabled()) {
  29. logger.debug("当前操作methodName=" + methodName + "不需要检查登录情况");
  30. }
  31. return true;
  32. }
  33. if (null == request.getSession().getAttribute(CommonConstants.SESSION_KEY_USER)) {
  34. logger.warn("当前操作" + methodName + "用户未登录,ip=" + request.getRemoteAddr());
  35. response.getWriter().write(JsonConvertor.convertFailResult(ErrorCodeEnum.NOT_LOGIN).toString()); // 返回错误信息
  36. return false;
  37. }
  38. return true;
  39. }
  40. @Override
  41. public void postHandle(HttpServletRequest request, HttpServletResponse response,
  42. Object handler, ModelAndView modelAndView) throws Exception {
  43. }
  44. @Override
  45. public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
  46. Object handler, Exception ex) throws Exception {
  47. }
  48. }

上面我们定义了一个登录拦截器,首先使用反射来判断方法上是否被 @NoLogin 注解:

  1. NoLogin noLogin = handlerMethod.getMethod().getAnnotation(NoLogin.class);

然后判断类是否被 @NoLogin 注解:

  1. noLogin = handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoLogin.class);

如果被注解了,就返回 true,如果没有被注解,就判断是否已经登录,没有登录则返回错误信息给前台和false. 这是一个简单的使用 注解 和 过滤器 来进行权限处理的例子。扩展开来,那么我们就可以使用注解,来表示某方法或者类,只能被具有某种角色,或者具有某种权限的用户所访问,然后在过滤器中进行判断处理。

3. spring的bean容器相关的注解

1)@Autowired 是我们使用得最多的注解,其实就是 autowire=byType 就是根据类型的自动注入依赖(基于注解的依赖注入),可以被使用再属性域,方法,构造函数上。

2)@Qualifier 就是 autowire=byName, @Autowired注解判断多个bean类型相同时,就需要使用 @Qualifier("xxBean") 来指定依赖的bean的id:

  1. @Controller
  2. @RequestMapping("/user")
  3. public class HelloController {
  4. @Autowired
  5. @Qualifier("userService")
  6. private UserService userService;

3)@Resource 属于JSR250标准,用于属性域额和方法上。也是 byName 类型的依赖注入。使用方式:@Resource(name="xxBean"). 不带参数的 @Resource 默认值类名首字母小写。

4)JSR-330标准javax.inject.*中的注解(@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton)。@Inject就相当于@Autowired, @Named 就相当于 @Qualifier, 另外 @Named 用在类上还有 @Component的功能。

5)@Component, @Controller, @Service, @Repository, 这几个注解不同于上面的注解,上面的注解都是将被依赖的bean注入进入,而这几个注解的作用都是生产bean, 这些注解都是注解在类上,将类注解成spring的bean工厂中一个一个的bean。@Controller, @Service, @Repository基本就是语义更加细化的@Component。

6)@PostConstruct 和 @PreDestroy 不是用于依赖注入,而是bean 的生命周期。类似于 init-method(InitializeingBean) destory-method(DisposableBean)

4. spring中注解的处理

spring中注解的处理基本都是通过实现接口 BeanPostProcessor 来进行的:

  1. public interface BeanPostProcessor {
  2. Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
  3. Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
  4. }

相关的处理类有: AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,  RequiredAnnotationBeanPostProcessor

这些处理类,可以通过 <context:annotation-config/> 配置隐式的配置进spring容器。这些都是依赖注入的处理,还有生产bean的注解(@Component, @Controller, @Service, @Repository)的处理:

<context:component-scan base-package="net.aazj.service,net.aazj.aop" />

这些都是通过指定扫描的基包路径来进行的,将他们扫描进spring的bean容器。注意 context:component-scan 也会默认将 AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor 配置进来。所以<context:annotation-config/>是可以省略的。另外context:component-scan也可以扫描@Aspect风格的AOP注解,但是需要在配置文件中加入 <aop:aspectj-autoproxy/> 进行配合。

5. Spring注解和JSR-330标准注解的区别

深入理解spring中的各种注解的更多相关文章

  1. 深入理解spring中的各种注解(转)

    Spring中的注解大概可以分为两大类: 1)spring的bean容器相关的注解,或者说bean工厂相关的注解: 2)springmvc相关的注解. spring的bean容器相关的注解,先后有:@ ...

  2. Spring 中aop切面注解实现

    spring中aop的注解实现方式简单实例   上篇中我们讲到spring的xml实现,这里我们讲讲使用注解如何实现aop呢.前面已经讲过aop的简单理解了,这里就不在赘述了. 注解方式实现aop我们 ...

  3. 通过BeanPostProcessor理解Spring中Bean的生命周期

    通过BeanPostProcessor理解Spring中Bean的生命周期及AOP原理 Spring源码解析(十一)Spring扩展接口InstantiationAwareBeanPostProces ...

  4. 第5章—构建Spring Web应用程序—关于spring中的validate注解后台校验的解析

    关于spring中的validate注解后台校验的解析 在后台开发过程中,对参数的校验成为开发环境不可缺少的一个环节.比如参数不能为null,email那么必须符合email的格式,如果手动进行if判 ...

  5. Spring中的常用注解

    Spring中的常用注解 1.@Controller 标识一个该类是Spring MVC controller处理器,用来创建处理http请求的对象.

  6. JavaEE开发之Spring中的条件注解组合注解与元注解

    上篇博客我们详细的聊了<JavaEE开发之Spring中的多线程编程以及任务定时器详解>,本篇博客我们就来聊聊条件注解@Conditional以及组合条件.条件注解说简单点就是根据特定的条 ...

  7. spring中aop的注解实现方式简单实例

    上篇中我们讲到spring的xml实现,这里我们讲讲使用注解如何实现aop呢.前面已经讲过aop的简单理解了,这里就不在赘述了. 注解方式实现aop我们主要分为如下几个步骤(自己整理的,有更好的方法的 ...

  8. JavaEE开发之Spring中的条件注解、组合注解与元注解

    上篇博客我们详细的聊了<JavaEE开发之Spring中的多线程编程以及任务定时器详解>,本篇博客我们就来聊聊条件注解@Conditional以及组合条件.条件注解说简单点就是根据特定的条 ...

  9. 浅谈spring中AOP以及spring中AOP的注解方式

    AOP(Aspect Oriented Programming):AOP的专业术语是"面向切面编程" 什么是面向切面编程,我的理解就是:在不修改源代码的情况下增强功能.好了,下面在 ...

随机推荐

  1. IOS开发UI基础UIView

    主要介绍下UIView得基本概念和一些属性的介绍至于属性的用户后面会由详细的介绍 -.UIView基本概念 1.什么是控件? 屏幕上所有的UI元素都叫做控件 (也有很多书中叫做视图 组件) 比如 按钮 ...

  2. C#开发体感游戏 Kinect应用知识

    Kinect首先是一个XBox 360外接体感设备,通过无线方式捕捉动作感知.由PrimeSense提供Range Camera技术,同类产品如任天堂Wii.Play Station Move,必须让 ...

  3. 【循序渐进学Python】12.Python 正则表达式简介

    正表达式就是一段匹配文本片段的模式,在Python 中 re 模块包含了对正则表达式(regular expression)的支持. 1. 正则表达式的基本概念 1. 通配符 点号( . )可以匹配换 ...

  4. SQL Server密码管理的六个危险判断

    当管理SQL Server内在的帐户和密码时,我们很容易认为这一切都相当的安全.但实际上并非如此.在这里,我们列出了一些对于SQL Server密码来说非常危险的判断. 当管理SQL Server内在 ...

  5. net 数据库连接详解 相当经典啊

    ADO.NET与抽水的故事 ADO.NET是微软新一代.NET数据库的访问架构,ADO是ActiveX Data Objects的缩写.ADO.NET是数据库应用程序和数据源之间沟通的桥梁,主要提供一 ...

  6. python输出excel能够识别的utf-8格式csv文件

    http://blog.csdn.net/azhao_dn/article/details/16989777 可能大家都遇到过,python在输出的csv文件中如果有utf-8格式的中文,那么在使用e ...

  7. [PHP] 命令行执行整合pathinfo模拟定时任务

    命令行模式下,根据传参,调用不同控制器.控制器中根据配置定时执行指定方法 Application.php <?php class Application{ public static funct ...

  8. [moka同学摘录]在Centos 6.5下成功安装和配置了vim7.4

    来源:https://my.oschina.net/gzyh/blog/266097 资源下载地址: 链接:http://pan.baidu.com/s/1kVuaV5P 密码:xkq9   摘要: ...

  9. jdk1.8 ThreadPoolExecutor实现机制分析

    ThreadPoolExecutor几个重要的状态码字段 private static final int COUNT_BITS = Integer.SIZE - 3; private static ...

  10. 以Self Host的方式来寄宿Web API

    Common类及实体定义.Web API的定义请参见我的上一篇文章:以Web Host的方式来寄宿Web API. 一.以Self Host寄宿需要新建一个Console控制台项目(SelfHost) ...