Spring常用註解

2021-07-13 12:38:32 字數 2056 閱讀 3701

spring常用註解

1 引入context命名空間(在spring的配置檔案中),配置檔案如下:

xml**  

xmlns:context=""

/spring-context-2.5.xsd   

開啟配置

spring 會自動掃瞄cn.pic包下面有註解的類,完成bean的裝配。

xml**  

xmlversion="1.0"

encoding="utf-8"

?>

<

beans

xmlns=""

xmlns:xsi=""

xmlns:context=""

xsi:schemalocation="    

/spring-beans-2.5.xsd    

/spring-context-2.5.xsd">

<

context:component-scan

base-package="cn.pic"

/>

beans

>

2 在classpath中加入註解用的jar包

lib\j2ee\common-annotations.jar

spring 的context:component-scan掃瞄支援掃瞄jar包的方法:

eclipse自帶的jar打包程式,預設打包的時候有個選項<

add directory entries>

沒有勾選,只要勾選了,就可以了.

-----------常用註解--------

--定義bean的註解

@controller

@controller("bean的名稱")

定義控制層bean,如action

@service          

@service("bean的名稱")

定義業務層bean

@repository   

@repository("bean的名稱")

定義dao層bean

@component  

定義bean, 不好歸類時使用.

--自動裝配bean(選用一種註解就可以)

@autowired  (srping提供的)

預設按型別匹配,自動裝配(srping提供的),可以寫在成員屬性上,或寫在setter方法上

@autowired(required=true)  

一定要找到匹配的bean,否則拋異常。 預設值就是true 

@autowired

@qualifier("bean的名字") 

按名稱裝配bean,與@autowired組合使用,解決按型別匹配找到多個bean問題。

@resource   jsr-250提供的

預設按名稱裝配,當找不到名稱匹配的bean再按型別裝配.

可以寫在成員屬性上,或寫在setter方法上

可以通過@resource(name="beanname") 指定被注入的bean的名稱, 要是未指定name屬性, 預設使用成員屬性的變數名,一般不用寫name屬性.

@resource(name="beanname")指定了name屬性,按名稱注入但沒找到bean, 就不會再按型別裝配了.

@inject   是jsr-330提供的

按型別裝配,功能比@autowired少,沒有使用的必要。

--定義bean的作用域和生命過程

@scope("prototype")

值有:singleton,prototype,session,request,session,globalsession

@postconstruct 

相當於init-method,使用在方法上,當bean初始化時執行。

@predestroy 

相當於destory-method,使用在方法上,當bean銷毀時執行。

--宣告式事務

@transactional  

Spring常用註解

在spring中常用的註解 autowired註解 不推薦使用,建議使用 resource autowired可以對成員變數 方法和建構函式進行標註,來完成自動裝配的工作。autowired的標註位置不同,它們都會在spring在初始化這個bean時,自動裝配這個屬性。要使 autowired能夠工...

spring常用註解

1 引入context命名空間 在spring的配置檔案中 配置檔案如下 xml 收藏 xmlns context spring context 2.5.xsd 開啟配置 spring 會自動掃瞄cn.pic包下面有註解的類,完成bean的裝配。xml xmlns xmlns xsi xmlns c...

Spring常用註解

controller 標註乙個控制器元件類。scope 預設是單例模式,即scope singleton 另外scope還有prototype request session global session作用域 scope prototype 多例 method 定義處理方法的 http metho...