設計模式——Spring註解編程模型

1. 引言

模式註解使框架的配置變得簡潔明瞭,從Spring Framework 3.1開始Spring開始全面支持面向註解配置,其中一些核心註解如下

Spring模式註解:

Spring 註解 場景說明 起始版本
@Repository 數據倉庫模式註解 2.0
@Component 通用組件模式註解 2.5
@Service 服務模式註解 2.5
@Controller Web控制器模式註解 2.5
@Configuration 配置類模式註解 3.0

裝配註解:

Spring 註解 場景說明 起始版本
@ImportResource 替換XML元素 2.5
@Import 導入bean或者@configuration配置類 3.0
@ComponentScan 掃描指定package下標註Spring模式註解的類 3.1

依賴注入註解如下表所示:

Spring 註解 場景說明 起始版本
@Autowired Bean依賴注入,支持多種依賴查找方式 2.5
@Qualifier 細粒度限定@autowired注入 2.5
Spring 註解 場景說明 起始版本
@Resource @Bean依賴注入,僅支持名稱依賴查找方式 2.5

Bean定義註解如下表所示

Spring 註解 場景說明 起始版本
@Bean 替換XML元素 3.0
@DependsOn 替換XML元素 3.0
@Lazy 替換XML元素 3.0
@Primary 替換XML元素 3.0
@Role 替換XML元素 3.1
@Lookup 替換XML元素 4.1

Spring條件裝配註解:

Spring 註解 場景說明 起始版本
@Profile 配置化條件裝配 3.1
@Conditional 編程條件裝配 4.0

配置屬性註解:

Spring 註解 場景說明 起始版本
@PropertySource 配置屬性抽象 3.1
@PropertySources @PropertySource集合註解 4.0

生命週期回調註解

Java 註解 場景說明 起始版本
@PostConstruct 替換XML元素 2.5
@PreDestroy 替換XML元素 2.5

可以標註註解的屬性

Java 註解 場景說明 起始版本
@AliasFor 別名註解屬性,實現複用的目的 4.2

性能註解:

Java 註解 場景說明 起始版本
@Indexed 提升Spring模式註解的掃描效率 5.0

2. Spring註解編程模型

主要有四個方面分別是:

  • 元註解(Meta-Annotations)
  • Spring模式註解(Stereotype Annotations)
  • Spring組合註解(Composed Annotations)
  • Spring註解屬性別名和覆蓋(Attribute Aliases and Overrides)

2.1 元註解(Meta-Annotations)

元註解指一個能聲明在其他註解上的註解,如果一個註解標註在其他註解上,那麼他就是元註解。根據Java語言規範,註解之間不存在繼承關係,因此可以通過元註解來註解到另一個註解達到“派生”的作用,這種“派生”特性需要確保註解之間的屬性方法簽名完全一致.

2.2 Spring模式註解(Stereotype Annotations)

引用Spring重的Wiki描述裏的一句話

A sterotype annotation is an annotation that is used to declare the role that a componnet plays within the application.

簡而言之Stereotype Annotations就是說明組件扮演的角色,以@Component註解爲例,@Service、@Repository、@Controler、@RestController及@Configuration都包含@Component註解,所以包含@Component的功能,同時他們在不同的場景下扮演不同的角色。在Spring Framework 3.x 之前以@Component註解爲例,只能識別單層次的@Component派生註解,在Spring Framework 3.x 之後可以遞歸識別多層次的@Component派生註解。
Spring初始化過程中掃描註解的過程簡單的原理我在另一篇Java基礎 註解中有簡單分析了一下,主要過程就是根據配置的basePackage屬性到該路徑下搜索有相應註解標記的類,然後注入到容器當中。需要另外注意的是Spring在掃描的過程中還會有excludeFilters和includeFilters,排除excludeFilters中的註解,屬於includeFilters中的註解將會通過篩選條件(默認初始化時includeFilters會加入@Component)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章