Spring中的注解大概可以分为两大类:
-
spring的bean容器相关的注解,或者说bean工厂相关的注解;
spring的bean容器相关的注解有:@Required, @Autowired, @PostConstruct, @PreDestory。还有Spring3.0开始支持的JSR-330标准javax.inject.*中的注解(@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton). -
springmvc相关的注解。
springmvc相关的注解有:@Controller,@RequestMapping,@RequestParam, @ResponseBody等等。
要理解Spring中的注解,先要理解Java中的注解。
Java中的注解
Java中1.5中开始引入注解,我们最熟悉的应该是:@Override, 它的定义如下:
/**
* Indicates that a method declaration is intended to override a
* method declaration in a supertype. If a method is annotated with
* this annotation type compilers are required to generate an error
* message unless at least one of the following conditions hold:
* The method does override or implement a method declared in a
* supertype.
* The method has a signature that is override-equivalent to that of
* any public method declared in Object.
*
* @author Peter von der Ahé
* @author Joshua Bloch
* @jls 9.6.1.4 @Override
* @since 1.5
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
从注释,我们可以看出,@Override的作用是,提示编译器,使用了**@Override注解的方法必须override父类或者java.lang.Object中的一个同名方法,或者实现一个接口**。我们看到@Override的定义中使用到了 @Target, @Retention,它们就是所谓的“元注解”——就是定义注解的注解,或者说注解注解的注解。
使用元注解来自定义注解和处理自定义注解
有了元注解,那么我就可以使用它来自定义我们需要的注解。结合自定义注解和AOP(面向切面/方法编程)或者过滤器,是一种十分强大的武器。比如可以使用注解来实现权限的细粒度的控制——在类或者方法上使用权限注解,然后在AOP或者过滤器中进行拦截处理。下面是一个关于登录的权限的注解的实现:
/**
* 不需要登录注解
*/
@Target({
ElementType.METHOD, ElementType.TYPE
}
)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoLogin {
}
我们自定义了一个注解 @NoLogin, 可以被用于 方法 和 类 上,注解一直保留到运行期,可以被反射读取到。该注解的含义是:被 @NoLogin 注解的类或者方法,即使用户没有登录,也是可以访问的。下面就是对注解进行处理了:
/**
* 检查登录拦截器
* 如不需要检查登录可在方法或者controller上加上@NoLogin
*/
public class CheckLoginInterceptor implements HandlerInterceptor {
private static final