Spring 註解式依賴注入

2021-08-22 04:54:55 字數 2912 閱讀 3645

在context.xml檔案新增下列**,啟用註解式依賴注入。

其中base-package的值改為所要掃瞄的包路徑。這裡設定為 com.diko.first包下的所有類。

@component任何乙個交給spring管理的類都可以使用@component註解來注釋。@component註解基本可以放在任何可受spring管理的類的頭上,但是@component不推薦使用,盡量使用下面三個代替。

@repository主要用於注釋dao層的bean,效果等效於@component,但是使用範圍僅限於dao層

@service主要用於注釋業務層的bean,效果等效與@component,但是使用範圍僅限於業務層。

@controller主要用於注釋控制層的bean,效果等效與@component,但是使用範圍僅限於控制層,也就是strut框架中的action,或者spring mvc中的controller。

@autowired注釋可以在 setter 方法中被用於自動連線 bean,當 spring遇到乙個在 setter 方法中使用的 @autowired 注釋,它會在方法中檢視執行bytype進行自動連線。

@required注釋應用於 bean 屬性的 setter 方法,它表明受影響的 bean 屬性在配置時必須放在 xml 配置檔案中,否則容器就會丟擲乙個 beaninitializationexception 異常。

@qualifier可以使用@qualifier注釋和@autowired注釋通過指定哪乙個真正的 bean 將會被裝配來消除混亂。

@resource與@autowired註解大致一致,但是@resource預設按照名稱(byname)方式進行bean匹配,而@autowired預設按照型別(bytype)方式進行bean匹配。

@component未指定bean id,將類交給spring 管理:

@component

@aspect

public class allservicepointcut

}

@component指定bean id,將類交給spring 管理:

@component("allservicepointcut")

@aspect

public class allservicepointcut

}

@repository註解,這個給出指定id的寫法,未指定id寫法同上

@repository("exceptionlogdao")

public class exceptionlogdaoimpl implements iexceptionlogdao

@override

public void add(exceptionlogmodel exceptionlog) throws exception

}

@service的使用,類似@repository

@service

public class mailserviceimpl implements imailservice

}

@controller類似於@service@repository用法,這裡不給出demo。

@autowired的使用,通過bytype進行依賴注入

@aspect

public class servicemethodadvice

@afterthrowing(value="allservicepointcut.allservicepoint()",throwing="exception")

public void serviceexceptionhandler(joinpoint jp,exception exception) throws exception

}

@required表明受影響的 bean 屬性在配置時必須放在 xml 配置檔案中,否則丟擲異常,這裡不給出demo。

@qualifier通過指定id(byname)進行依賴注入

@aspect

@component

public class servicemethodadvice

@around(value="allservicepointcut.allservicepoint()")

public object runaroundmethod(proceedingjoinpoint pjp) throws throwable

}

@resource的使用

@aspect

@component

public class servicemethodadvice

@around(value="allservicepointcut.allservicepoint()")

public object runaroundmethod(proceedingjoinpoint pjp) throws throwable

}

自己總結的Spring註解式依賴注入規則

根據多次反覆試驗,目前看起來注入規則如下,小夥伴們如果發現有不正確的,歡迎指出 spring 版本 4.3.2realease 前提 只有手動指定過name的bean才能通過byname方式找到 extends和implements也算type匹配 步驟如下 如果 resource沒有指定name,...

spring的依賴注入 註解版

要說的都在註解裡面了 建立person和student類 public class person public student getstudent public class student 測試 test public void test4 輸出就是hello spring的類掃瞄 compone...

Spring 使用註解實現依賴注入

依賴注入 本質就是對類中的變數進行賦值操作!spring 使用註解標註類,spring容器通過包掃瞄註解,將這些標註了spring註解的類管理起來。1 service註解 標註在乙個service層的業務類上,告訴spring容器這是乙個service層業務類,spring就會自動建立這個類的例項,...