Spring中的註解大概能夠分爲兩大類:java
spring的bean容器相關的註解有:@Required, @Autowired, @PostConstruct, @PreDestory。還有Spring3.0開始支持的JSR-330標準javax.inject.*中的註解(@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton).spring
springmvc相關的註解有:@Controller,@RequestMapping,@RequestParam, @ResponseBody等等。bash
要理解Spring中的註解,先要理解Java中的註解。mvc
Java中1.5中開始引入註解,咱們最熟悉的應該是:@Override, 它的定義以下:app
/**
* 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,它們就是所謂的「元註解」——就是定義註解的註解,或者說註解註解的註解(暈了…)。less
咱們看下@Retentionide
/**
* Indicates how long annotations with the annotated type are to
* be retained. If no Retention annotation is present on
* an annotation type declaration, the retention policy defaults to
* RetentionPolicy.CLASS.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}複製代碼
@Retention用於提示註解被保留多長時間,有三種取值:函數
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}複製代碼
RetentionPolicy.SOURCE 保留在源碼級別,被編譯器拋棄(@Override就是此類); RetentionPolicy.CLASS被編譯器保留在編譯後的類文件級別,可是被虛擬機丟棄;post
RetentionPolicy.RUNTIME保留至運行時,能夠被反射讀取。ui
再看 @Target:
package java.lang.annotation;
/**
* Indicates the contexts in which an annotation type is applicable. The
* declaration contexts and type contexts in which an annotation type may be
* applicable are specified in JLS 9.6.4.1, and denoted in source code by enum
* constants of java.lang.annotation.ElementType
* @since 1.5
* @jls 9.6.4.1 @Target
* @jls 9.7.4 Where Annotations May Appear
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}複製代碼
@Target用於提示該註解使用的地方,取值有:
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
* @since 1.8
*/
TYPE_USE
}複製代碼
分別表示該註解能夠被使用的地方:1)類,接口,註解,enum; 2)屬性域;3)方法;4)參數;5)構造函數;6)局部變量;7)註解類型;8)包
因此:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}複製代碼
表示 @Override 只能使用在方法上,保留在源碼級別,被編譯器處理,而後拋棄掉。
還有一個常常使用的元註解 @Documented :
/**
* Indicates that annotations with a type are to be documented by javadoc
* and similar tools by default. This type should be used to annotate the
* declarations of types whose annotations affect the use of annotated
* elements by their clients. If a type declaration is annotated with
* Documented, its annotations become part of the public API
* of the annotated elements.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}複製代碼
表示註解是否能被 javadoc 處理並保留在文檔中。
有了元註解,那麼我就可使用它來自定義咱們須要的註解。結合自定義註解和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 Logger logger = Logger.getLogger(CheckLoginInterceptor.class);
@Override
public Boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
logger.warn("當前操做handler不爲HandlerMethod=" + handler.getClass().getName() + ",req="
+ request.getQueryString());
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
String methodName = handlerMethod.getMethod().getName();
// 判斷是否須要檢查登陸
NoLogin noLogin = handlerMethod.getMethod().getAnnotation(NoLogin.class);
if (null != noLogin) {
if (logger.isDebugEnabled()) {
logger.debug("當前操做methodName=" + methodName + "不須要檢查登陸狀況");
}
return true;
}
noLogin = handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoLogin.class);
if (null != noLogin) {
if (logger.isDebugEnabled()) {
logger.debug("當前操做methodName=" + methodName + "不須要檢查登陸狀況");
}
return true;
}
if (null == request.getSession().getAttribute(CommonConstants.SESSION_KEY_USER)) {
logger.warn("當前操做" + methodName + "用戶未登陸,ip=" + request.getRemoteAddr());
response.getWriter().write(JsonConvertor.convertFailResult(ErrorCodeEnum.NOT_LOGIN).toString());
// 返回錯誤信息
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
}
}複製代碼
上面咱們定義了一個登陸攔截器,首先使用反射來判斷方法上是否被 @NoLogin 註解:
NoLogin noLogin = handlerMethod.getMethod().getAnnotation(NoLogin.class);複製代碼
而後判斷類是否被 @NoLogin 註解:
noLogin = handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoLogin.class);複製代碼
若是被註解了,就返回 true,若是沒有被註解,就判斷是否已經登陸,沒有登陸則返回錯誤信息給前臺和false. 這是一個簡單的使用 註解 和 過濾器 來進行權限處理的例子。
擴展開來,那麼咱們就可使用註解,來表示某方法或者類,只能被具備某種角色,或者具備某種權限的用戶所訪問,而後在過濾器中進行判斷處理。
@Autowired 是咱們使用得最多的註解,其實就是 autowire=byType 就是根據類型的自動注入依賴(基於註解的依賴注入),能夠被使用再屬性域,方法,構造函數上。
@Qualifier 就是 autowire=byName, @Autowired註解判斷多個bean類型相同時,就須要使用 @Qualifier("xxBean") 來指定依賴的bean的id:
@Controller
@RequestMapping("/user")
public class HelloController {
@Autowired
@Qualifier("userService")
private UserService userService;複製代碼
@Resource 屬於JSR250標準,用於屬性域和方法上。也是 byName 類型的依賴注入。使用方式:@Resource(name="xxBean"). 不帶參數的 @Resource 默認值類名首字母小寫。
JSR-330標準javax.inject.*中的註解(@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton)。@Inject就至關於@Autowired, @Named 就至關於 @Qualifier, 另外 @Named 用在類上還有 @Component的功能。
@Component, @Controller, @Service, @Repository, 這幾個註解不一樣於上面的註解,上面的註解都是將被依賴的bean注入進入,而這幾個註解的做用都是生產bean, 這些註解都是註解在類上,將類註解成spring的bean工廠中一個一個的bean。@Controller, @Service, @Repository基本就是語義更加細化的@Component。
@PostConstruct 和 @PreDestroy 不是用於依賴注入,而是bean 的生命週期。相似於 init-method(InitializeingBean) destory-method(DisposableBean)
spring中註解的處理基本都是經過實現接口 BeanPostProcessor 來進行的:
public interface BeanPostProcessor {
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}複製代碼
相關的處理類有:
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/> 進行配合。