Spring Component註釋用於將類別標記為Component。這表示當使用基於註釋的配置和類路徑掃描時,Spring框架將自動檢測這些類別以進行依賴注入。
Spring Component
通俗地說,Component負責某些操作。Spring框架提供了三個其他特定的註釋,用於將類別標記為Component。
Service
:表示該類別提供某些服務。我們的實用程式類別可以標記為Service類別。Repository
:此註釋表示該類別處理CRUD操作,通常與處理資料庫表格的DAO實現一起使用。Controller
:通常與網頁應用程式或REST網路服務一起使用,用於指定該類別為前端控制器,負責處理使用者請求並返回適當的回應。
請注意,所有這四個註釋都在 org.springframework.stereotype
套件中,並且是 spring-context
jar的一部分。 大多數情況下,我們的組件類將屬於其三個專門的註釋之一,因此您可能不會經常使用 @Component
註釋。
Spring組件示例
讓我們創建一個非常簡單的Spring Maven應用程序,以展示Spring組件註釋的使用方式,以及Spring如何使用基於註釋的配置和類路徑掃描來自動檢測它。 創建一個maven項目並添加以下Spring核心依賴項。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
這就是我們需要獲取spring框架核心功能的全部內容。 讓我們創建一個簡單的組件類並將其標記為 @Component
註釋。
package com.journaldev.spring;
import org.springframework.stereotype.Component;
@Component
public class MathComponent {
public int add(int x, int y) {
return x + y;
}
}
現在,我們可以創建一個基於註釋的Spring上下文並從中獲取 MathComponent
bean。
package com.journaldev.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringMainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.journaldev.spring");
context.refresh();
MathComponent ms = context.getBean(MathComponent.class);
int result = ms.add(1, 2);
System.out.println("Addition of 1 and 2 = " + result);
context.close();
}
}
只需像正常的Java應用程序一樣運行上面的類,您應該在控制台中獲得以下輸出。
Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy
Addition of 1 and 2 = 3
Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy
您是否意識到Spring的強大之處,我們無需做任何事情就可以將組件注入到Spring上下文中。 下圖顯示了我們的Spring組件示例項目的目錄結構。 我們還可以指定組件名稱,然後使用相同的名稱從spring上下文中獲取它。
@Component("mc")
public class MathComponent {
}
MathComponent ms = (MathComponent) context.getBean("mc");
雖然我使用了 @Component
注解與 MathComponent,但實際上它是一個服務類別,我們應該使用 @Service
注解。結果仍將保持不變。
你可以從我們的 GitHub 存儲庫 檢出該項目。
參考資料: API 文件
Source:
https://www.digitalocean.com/community/tutorials/spring-component