Spring 基於註解的配置
阿新 • • 發佈:2019-01-26
基於註解的配置
從 Spring 2.5 開始就可以使用註解來配置依賴注入。而不是採用 XML 來描述一個 bean 連線,你可以使用相關類,方法或欄位宣告的註解,將 bean 配置移動到元件類本身。
在 XML 注入之前進行註解注入,因此後者的配置將通過兩種方式的屬性連線被前者重寫。
註解連線在預設情況下在 Spring 容器中不開啟。因此,在可以使用基於註解的連線之前,我們將需要在我們的 Spring 配置檔案中啟用它。所以如果你想在 Spring 應用程式中使用的任何註解,可以考慮到下面的配置檔案。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> <!-- bean definitions go here --> </beans>
一旦 被配置後,你就可以開始註解你的程式碼,表明 Spring 應該自動連線值到屬性,方法和建構函式。讓我們來看看幾個重要的註解,並且瞭解它們是如何工作的:
序號 | 註解 & 描述 |
---|---|
1 | @Required
@Required 註解應用於 bean 屬性的 setter 方法。 |
2 | @Autowired
@Autowired 註解可以應用到 bean 屬性的 setter 方法,非 setter 方法,建構函式和屬性。 |
3 | @Qualifier
通過指定確切的將被連線的 bean,@Autowired 和 @Qualifier 註解可以用來刪除混亂。 |
4 | JSR-250 Annotations
Spring 支援 JSR-250 的基礎的註解,其中包括了 @Resource,@PostConstruct 和 @PreDestroy 註解。 |