- 概念理解 詳細的自行搜索
IOC:Inverse Of Control控制反轉
DI:Dependency Injection依賴注入
- 注入類型
Setter(常用)
UserService類(省略非關鍵性代碼)
Spring.xml
測試運行
運行結果:正確
構造方法
引用其他bean作爲參數
新建bean作爲參數
通過參數類型識別
通過下標識別
接口注入(不建議使用)
- Bean 的ID和NAME區別
Id vs name
name中可以加入特殊字符比如#,實際作用不大
實際上id和name一樣的
- 簡單屬性的注入
示範:
User類如下(省去getter/setter部分代碼)
Spring.xml中添加
測試運行
運行結果 正確輸出了
- Bean的Scope屬性(範圍)
singleton第一個單例模式,就是你每次getBean得到的是同一個
運行結果爲trueprototype第二個原型模式,每次getBean給你造一個新的每次造出來的==結果爲false
同上做法運行結果爲false,截圖就不貼了
- Bean的集合注入
-
Properties
Set
List
Map
- 自動裝配autowire屬性
-
單個配
全部配
兩個常用
byName 將bean中名字和屬性名相同的裝載
byType 將bean中class類型相同的裝載,不得出現多個,會報錯,可使用qualifier區分
- 生命週期LifeCycle
- lazy-init屬性 當爲true的時候spring容器初始化的時候不會創建這個Bean,使用情況在啓動特別慢的情況下,避免加載暫時不用的bean提高速度
-
單個添加
全部添加
init-method bean初始化的時候先調用此方法
destroy-method銷燬的時候調方法(不要和scope=”prototype”一起使用,因爲在此情況下spring 不持續監控對象的整個生命週期了,不要去研究)
- Annotation註解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">紅色標出的是需要添加的
beans中添加
<context:annotation-config/>
上面一句包含了下面四個註解的處理器
就可以使用註解了
使用@Component 、@Controller、@Service、@Repository標記過的類能被識別爲Bean
語法
自動注入
@Autowired (默認byType)
-
自動從beans中找匹配的對象注入
當beans中存在多個同類型bean時使用@Qualifier(“beanname”)來指定使用哪裏bean來注入(bean的name作爲一個默認的qualifier使用)
示範如下
定義qualifier屬性
@Autowired(required=false)意思是如果沒有找到能注入的bean也沒關係
@Resource(name=”n”) 常用,(不寫名字的時候默認byName,找不到嘗試byType)
如下例子釋義:從beans中拿name爲u的bean作爲參數傳入
@Component 指定名字的寫法 @Component(“name”)
下面意思爲從com.spring.bean包下掃描組件(包括子包)
<context:component-scan base-package="com.spring.bean"/>
-
註解指定屬性
例如scope
註解:@Scope(“prototype”)
Init-method destroy-method
註解: @PosstConstruct @PreDestroy -