Spring註解學習

2021-10-24 18:15:50 字數 2638 閱讀 8264

< context :component-scan base-package = 「com.acg」/>

bean標籤→ 註解

寫在類的定義上

@component

@service

@repository

@controller→ springmvc的註解

如果沒有指定id,預設的元件id是類名的首字母小寫

,或者為指定元件id

@service(「userservice」)

給元件成員變數注入例項 →**於容器

值屬性@value(「tuzhiwei」)

string username;

@value(「18」)

integer age;

值也可以寫在配置檔案上→properties

< comtext:property-placeholder location = 「classpath:配置檔案的名」/>

去寫key的時候建議加上字首

userservice.username=tuzhiwei

userservuce.age=18

引用配置檔案中的key

@value 註解在元件中使用

@value ("$")

string name;

@value("$")

integer age;

spring配置檔案中也可以使用

< bean class=「***」>

< property name = 「username」 value="use

rser

vice

.use

rnam

e∗∗"

/>

oper

tyna

me=a

geva

lue=

"∗

∗**"/> < property name = age value="**

userse

rvic

e.us

erna

me∗∗

"/>

oper

tyna

me=a

geva

lue=

"∗∗"/>

< /bean>

@autowired

預設是按照型別注入的,如果容器中該型別的元件只有乙個,可以直接使用@autowired

也可以按照元件id注入,以所在的成員變數名作為元件id進行引入。

@autowired+@qualifier

通過qualifier執行元件id

@autowired

@qualifier(「userdaoimpl」)

userdaouserdao;

使用@qualifier註解的value屬性指定元件id

@resource

預設按照型別注入,也可以指定元件id→使用其name屬性指定元件id

@resource(name = 「userdaoimpl2」)

userdao userdao;

可以使用name屬性值指定元件id

引申@autowired註解的使用

也可以加在方法上→功能主要是給其他元件賦值

@autowired

public void setuserdao***(@qualifier(userdaoimpl) userdao userdao)

@component

@scope(「prototype」) 可以指定scope,如果為singleton可以省略不寫

init-method→寫的方法名→@postconstruct

destroy-method→寫的方法名→@predestroy

註解寫在元件中的方法上

@component

public class lifecyclebean

@predestroy

public void destroy()

}spring-test

< dependency>

< groupid>org.spring-test< /groupid>

< artifactid>spring-test< /artifactid>

< version>5.2.9.release< /version>

< scope>test< /scope>

< /dependency>

version應該和其他spring依賴的版本相同

@autowired

userservice userservice;

@test

public void mytest1()

spring註解學習

宣告bean的註解 注入bean的註解 配置檔案的註解 aop切面程式設計註解 spring 常用配置 postconstruct 在建構函式執行完之後執行 predestroy 在 bean 銷毀之前執行 activeprofiles 用來宣告活動的 profile profile 為不同環境下使...

spring註解學習

如果使用以下註解,請在spring配置bean檔案中加上 讓它知道它去 掃瞄你的註解 component 形式 component value component 作用 用於把當前類物件存入 spring 容器中 屬性 value 用於指定 bean 的 id,預設是當前類名,且首字母改小寫 當值只...

Spring 註解學習筆記

宣告bean的註解 注入bean的註解 配置檔案的註解 aop切面程式設計註解 spring 常用配置 postconstruct 在建構函式執行完之後執行 predestroy 在 bean 銷毀之前執行 activeprofiles 用來宣告活動的 profile profile 為不同環境下使...