最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

快速理解spring中的各種注解

 更新時(shí)間:2017年12月08日 14:39:19   作者:滄海一滴  
這篇文章主要介紹了快速理解spring中的各種注解,具有一定借鑒價(jià)值,需要的朋友可以了解下。

Spring中的注解大概可以分為兩大類(lèi):

1)spring的bean容器相關(guān)的注解,或者說(shuō)bean工廠相關(guān)的注解;

2)springmvc相關(guān)的注解。

spring的bean容器相關(guān)的注解,先后有:@Required, @Autowired, @PostConstruct, @PreDestory,還有Spring3.0開(kāi)始支持的JSR-330標(biāo)準(zhǔn)javax.inject.*中的注解(@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton).

springmvc相關(guān)的注解有:@Controller, @RequestMapping, @RequestParam, @ResponseBody等等。

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

1. Java中的注解

Java中1.5中開(kāi)始引入注解,我們最熟悉的應(yīng)該是:@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 {
}

從注釋?zhuān)覀兛梢钥闯?,@Override的作用是,提示編譯器,使用了@Override注解的方法必須override父類(lèi)或者java.lang.Object中的一個(gè)同名方法。我們看到@Override的定義中使用到了 @Target, @Retention,它們就是所謂的“元注解”——就是定義注解的注解,或者說(shuō)注解注解的注解(暈了...)。我們看下@Retention

/**
 * 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用于提示注解被保留多長(zhǎng)時(shí)間,有三種取值:

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 保留在源碼級(jí)別,被編譯器拋棄(@Override就是此類(lèi)); RetentionPolicy.CLASS被編譯器保留在編譯后的類(lèi)文件級(jí)別,但是被虛擬機(jī)丟棄;

RetentionPolicy.RUNTIME保留至運(yùn)行時(shí),可以被反射讀取。

再看 @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)類(lèi),接口,注解,enum; 2)屬性域;3)方法;4)參數(shù);5)構(gòu)造函數(shù);6)局部變量;7)注解類(lèi)型;8)包

所以:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

表示 @Override 只能使用在方法上,保留在源碼級(jí)別,被編譯器處理,然后拋棄掉。

還有一個(gè)經(jīng)常使用的元注解 @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 處理并保留在文檔中。

2. 使用 元注解 來(lái)自定義注解 和 處理自定義注解

有了元注解,那么我就可以使用它來(lái)自定義我們需要的注解。結(jié)合自定義注解和AOP或者過(guò)濾器,是一種十分強(qiáng)大的武器。比如可以使用注解來(lái)實(shí)現(xiàn)權(quán)限的細(xì)粒度的控制——在類(lèi)或者方法上使用權(quán)限注解,然后在AOP或者過(guò)濾器中進(jìn)行攔截處理。下面是一個(gè)關(guān)于登錄的權(quán)限的注解的實(shí)現(xiàn):

/**
 * 不需要登錄注解
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoLogin {
}

我們自定義了一個(gè)注解 @NoLogin, 可以被用于 方法 和 類(lèi) 上,注解一直保留到運(yùn)行期,可以被反射讀取到。該注解的含義是:被 @NoLogin 注解的類(lèi)或者方法,即使用戶(hù)沒(méi)有登錄,也是可以訪(fǎng)問(wèn)的。下面就是對(duì)注解進(jìn)行處理了:

/**
 * 檢查登錄攔截器
 * 如不需要檢查登錄可在方法或者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("當(dāng)前操作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("當(dāng)前操作methodName=" + methodName + "不需要檢查登錄情況");
			}
			return true;
		}
		noLogin = handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoLogin.class);
		if (null != noLogin) {
			if (logger.isDebugEnabled()) {
				logger.debug("當(dāng)前操作methodName=" + methodName + "不需要檢查登錄情況");
			}
			return true;
		}
		if (null == request.getSession().getAttribute(CommonConstants.SESSION_KEY_USER)) {
			logger.warn("當(dāng)前操作" + methodName + "用戶(hù)未登錄,ip=" + request.getRemoteAddr());
			response.getWriter().write(JsonConvertor.convertFailResult(ErrorCodeEnum.NOT_LOGIN).toString());
			// 返回錯(cuò)誤信息
			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 {
	}
}

上面我們定義了一個(gè)登錄攔截器,首先使用反射來(lái)判斷方法上是否被 @NoLogin 注解:

NoLogin noLogin = handlerMethod.getMethod().getAnnotation(NoLogin.class);
然后判斷類(lèi)是否被 @NoLogin 注解:

noLogin = handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoLogin.class);
如果被注解了,就返回 true,如果沒(méi)有被注解,就判斷是否已經(jīng)登錄,沒(méi)有登錄則返回錯(cuò)誤信息給前臺(tái)和false. 這是一個(gè)簡(jiǎn)單的使用 注解 和 過(guò)濾器 來(lái)進(jìn)行權(quán)限處理的例子。擴(kuò)展開(kāi)來(lái),那么我們就可以使用注解,來(lái)表示某方法或者類(lèi),只能被具有某種角色,或者具有某種權(quán)限的用戶(hù)所訪(fǎng)問(wèn),然后在過(guò)濾器中進(jìn)行判斷處理。

3. spring的bean容器相關(guān)的注解

1)@Autowired 是我們使用得最多的注解,其實(shí)就是 autowire=byType 就是根據(jù)類(lèi)型的自動(dòng)注入依賴(lài)(基于注解的依賴(lài)注入),可以被使用再屬性域,方法,構(gòu)造函數(shù)上。

2)@Qualifier 就是 autowire=byName, @Autowired注解判斷多個(gè)bean類(lèi)型相同時(shí),就需要使用 @Qualifier("xxBean") 來(lái)指定依賴(lài)的bean的id:

@Controller
@RequestMapping("/user")
public class HelloController {
  @Autowired
  @Qualifier("userService")
  private UserService userService;

3)@Resource 屬于JSR250標(biāo)準(zhǔn),用于屬性域額和方法上。也是 byName 類(lèi)型的依賴(lài)注入。使用方式:@Resource(name="xxBean"). 不帶參數(shù)的 @Resource 默認(rèn)值類(lèi)名首字母小寫(xiě)。

4)JSR-330標(biāo)準(zhǔn)javax.inject.*中的注解(@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton)。@Inject就相當(dāng)于@Autowired, @Named 就相當(dāng)于 @Qualifier, 另外 @Named 用在類(lèi)上還有 @Component的功能。

5)@Component, @Controller, @Service, @Repository, 這幾個(gè)注解不同于上面的注解,上面的注解都是將被依賴(lài)的bean注入進(jìn)入,而這幾個(gè)注解的作用都是生產(chǎn)bean, 這些注解都是注解在類(lèi)上,將類(lèi)注解成spring的bean工廠中一個(gè)一個(gè)的bean。@Controller, @Service, @Repository基本就是語(yǔ)義更加細(xì)化的@Component。

6)@PostConstruct 和 @PreDestroy 不是用于依賴(lài)注入,而是bean 的生命周期。類(lèi)似于 init-method(InitializeingBean) destory-method(DisposableBean)

4. spring中注解的處理

spring中注解的處理基本都是通過(guò)實(shí)現(xiàn)接口 BeanPostProcessor 來(lái)進(jìn)行的:

public interface BeanPostProcessor {
  Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
  Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}

相關(guān)的處理類(lèi)有: AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor, RequiredAnnotationBeanPostProcessor

這些處理類(lèi),可以通過(guò) <context:annotation-config/> 配置隱式的配置進(jìn)spring容器。這些都是依賴(lài)注入的處理,還有生產(chǎn)bean的注解(@Component, @Controller, @Service, @Repository)的處理:

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

這些都是通過(guò)指定掃描的基包路徑來(lái)進(jìn)行的,將他們掃描進(jìn)spring的bean容器。注意 context:component-scan 也會(huì)默認(rèn)將 AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor 配置進(jìn)來(lái)。所以<context:annotation-config/>是可以省略的。另外context:component-scan也可以?huà)呙鐯Aspect風(fēng)格的AOP注解,但是需要在配置文件中加入 <aop:aspectj-autoproxy/> 進(jìn)行配合。

5. Spring注解和JSR-330標(biāo)準(zhǔn)注解的區(qū)別:

總結(jié)

以上就是本文關(guān)于快速理解spring中的各種注解的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專(zhuān)題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!

相關(guān)文章

  • 數(shù)據(jù)定位在java購(gòu)物車(chē)系統(tǒng)中的應(yīng)用

    數(shù)據(jù)定位在java購(gòu)物車(chē)系統(tǒng)中的應(yīng)用

    實(shí)現(xiàn)"加入購(gòu)物車(chē)"功能,數(shù)據(jù)定位至關(guān)重要,它通過(guò)用戶(hù)ID和商品ID等標(biāo)識(shí)符實(shí)現(xiàn)快速查詢(xún)和數(shù)據(jù)一致性,主鍵、外鍵和聯(lián)合索引等數(shù)據(jù)庫(kù)技術(shù),以及Redis緩存和并發(fā)控制策略如樂(lè)觀鎖或分布式鎖,共同保障了購(gòu)物車(chē)系統(tǒng)的查詢(xún)效率和數(shù)據(jù)安全,這些機(jī)制對(duì)高并發(fā)和大數(shù)據(jù)量的場(chǎng)景尤為重要
    2024-10-10
  • Java 虛擬機(jī)棧詳解分析

    Java 虛擬機(jī)棧詳解分析

    在線(xiàn)程創(chuàng)建時(shí),JVM會(huì)為每個(gè)線(xiàn)程創(chuàng)建一個(gè)單獨(dú)的??臻g。JVM的棧內(nèi)存不需要是連續(xù)的。JVM在棧上會(huì)進(jìn)行兩個(gè)操作:壓入和彈出棧幀。對(duì)于一個(gè)特定的線(xiàn)程來(lái)說(shuō),棧被稱(chēng)為運(yùn)行時(shí)棧。這個(gè)線(xiàn)程調(diào)用的每個(gè)方法會(huì)被存儲(chǔ)在響應(yīng)的運(yùn)行時(shí)棧里,包括了參數(shù),局部變量,計(jì)算媒介和其他數(shù)據(jù)
    2021-11-11
  • spring boot 使用@Async實(shí)現(xiàn)異步調(diào)用方法

    spring boot 使用@Async實(shí)現(xiàn)異步調(diào)用方法

    本篇文章主要介紹了spring boot 使用@Async實(shí)現(xiàn)異步調(diào)用方法,具有一定的參考價(jià)值,有興趣的可以了解一下。
    2017-04-04
  • 從架構(gòu)思維角度分析高并發(fā)下冪等性解決方案

    從架構(gòu)思維角度分析高并發(fā)下冪等性解決方案

    冪等(idempotent、idempotence)是一個(gè)數(shù)學(xué)與計(jì)算機(jī)學(xué)概念,常見(jiàn)于抽象代數(shù)中。?在編程中.一個(gè)冪等操作的特點(diǎn)是其任意多次執(zhí)行所產(chǎn)生的影響均與一次執(zhí)行的影響相同。冪等函數(shù),或冪等方法,是指可以使用相同參數(shù)重復(fù)執(zhí)行,并能獲得相同結(jié)果的函數(shù)
    2022-01-01
  • SpringBoot+Maven 多模塊項(xiàng)目的構(gòu)建、運(yùn)行、打包實(shí)戰(zhàn)

    SpringBoot+Maven 多模塊項(xiàng)目的構(gòu)建、運(yùn)行、打包實(shí)戰(zhàn)

    這篇文章主要介紹了SpringBoot+Maven 多模塊項(xiàng)目的構(gòu)建、運(yùn)行、打包實(shí)戰(zhàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05
  • Kotlin教程之基本數(shù)據(jù)類(lèi)型

    Kotlin教程之基本數(shù)據(jù)類(lèi)型

    這篇文章主要介紹了Kotlin教程之基本數(shù)據(jù)類(lèi)型的學(xué)習(xí)的相關(guān)資料,需要的朋友可以參考下
    2017-05-05
  • Java加密解密和數(shù)字簽名完整代碼示例

    Java加密解密和數(shù)字簽名完整代碼示例

    這篇文章主要介紹了Java加密解密和數(shù)字簽名完整代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-12-12
  • java中final修飾符實(shí)例分析

    java中final修飾符實(shí)例分析

    本文通過(guò)實(shí)例向我們展示了java中final修飾符的概念,final修飾的基本變量和引用類(lèi)型變量的區(qū)別。有需要的小伙伴可以參考下
    2014-11-11
  • Java判斷多個(gè)時(shí)間段是否重合的方法小結(jié)

    Java判斷多個(gè)時(shí)間段是否重合的方法小結(jié)

    這篇文章主要為大家詳細(xì)介紹了Java中判斷多個(gè)時(shí)間段是否重合的方法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2025-02-02
  • Spring源碼閱讀MethodInterceptor解析

    Spring源碼閱讀MethodInterceptor解析

    這篇文章主要為大家介紹了Spring源碼閱讀MethodInterceptor使用示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11

最新評(píng)論

望奎县| 甘泉县| 咸宁市| 道孚县| 白水县| 林周县| 隆尧县| 江达县| 万年县| 乌拉特前旗| 阳江市| 宜阳县| 南通市| 湖南省| 惠安县| 旬阳县| 张北县| 林西县| 龙海市| 扎兰屯市| 林芝县| 繁峙县| 满洲里市| 五峰| 赣州市| 巫山县| 泸溪县| 永靖县| 林芝县| 达州市| 衡南县| 新闻| 寿阳县| 托里县| 石阡县| 阳西县| 图木舒克市| 彰化市| 宝山区| 安图县| 安义县|