Spring Framework ‐ 使用註解管理 Bean - CCH0124/spring-sandbox GitHub Wiki

使用註解定義 Bean

Spring 提供了以下等多個註解,這些註解可以直接標註在 Java 類別上,將它們定義成 Spring Bean。

Annotation Description
@Component 此註解用於描述 Spring 中的 Bean,它是一個泛化的概念,僅表示容器中的一個元件(Bean),並且可以作用在應用的任何層次,例如 Service、Dao 層等。使用時只需將此註解標註在對應類別上即可。
@Repository 此註解用於將資料存取層(Dao 層)的類別標識為 Spring 中的 Bean,其功能與 @Component 相同。
@Service 此註解通常作用在業務層(Service 層),用於將業務層的類別標識為 Spring 中的 Bean,其功能與 @Component 相同。
@Controller 此註解通常作用在控制層(如 SpringMVC 的 Controller),用於將控制層的類別標識為 Spring 中的 Bean,其功能與 @Component 相同。

這 4 個註解功能上都是相同,唯一差別就是名稱上,僅為了直覺的體現其在不同的層次。

物件注入

@Autowired,預設根據類型裝配(by type)。

package org.springframework.beans.factory.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    boolean required() default true;
}
  1. Target,該註解可以標註在哪裡?
  • 建構方法上
  • 方法上
  • 參數上
  • 屬性上
  • 註解上
  1. required() 屬性預設為 true,表示在注入的時候要求被注入的 Bean 必須是存在的,如果不存在則報錯。如果 required 屬性設定為 false,表示注入的 Bean 存在或不存在都沒關係,存在的話就注入,不存在的話,也不報錯。

屬性注入