[TOC]
spring-ioc
spring快速入門
1抓督、導(dǎo)包
core燃少、context、expression铃在、bean
2阵具、引入schema文檔(類似dtd文檔)約束xml的文檔
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
3、通過(guò)xml配置bean
<!-- 1定铜、配置bean :new對(duì)象 -->
<bean class="com.hemi.bean.CandidateA" id="canA" />
<bean class="com.hemi.bean.CandidateB" id="canB" />
<bean class="com.hemi.bean.Personnel" id="personnel">
<!-- 通過(guò)構(gòu)造函數(shù)將候選人canA注入到人事部中 -->
<constructor-arg name="programme" ref="canB" />
</bean>
4阳液、創(chuàng)建測(cè)試類
//1、獲取xml文件揣炕,并且創(chuàng)建出ApplicationContext
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
//2帘皿、獲取人事部
Personnel personnel=(Personnel)context.getBean("personnel");
personnel.interview();
注入方式
- 構(gòu)造函數(shù)方式注入
- constructor-arg 構(gòu)造函數(shù)參數(shù)
- type 使用構(gòu)造函數(shù)參數(shù)類型
- name 使用構(gòu)造函數(shù)參數(shù)名
- index 使用位置 0代表構(gòu)造函數(shù)的第一個(gè)位置,1代表第二個(gè)位置畸陡,依次類推
- constructor-arg 構(gòu)造函數(shù)參數(shù)
例如:
<bean class="com.hemi.bean.Personnel" id="personnel">
<constructor-arg index="0" ref="canB" />
<constructor-arg index="1" ref="canA" />
</bean>
- get鹰溜、set方式注入
- property 代表屬性名稱
- value 屬性值
- ref 對(duì)象的引用
- property 代表屬性名稱
<bean class="com.hemi.bean.Personnel" id="personnel">
<property name="name" value="lili"></property>
<property name="programme" ref="canA"></property>
</bean>
- p名稱空間
在文檔定義中添加xmlns:p="http://www.springframework.org/schema/p"
<bean class="com.hemi.bean.Personnel" id="personnel" p:name="lisi"></bean>
總結(jié):
spring ioc容器特點(diǎn):
1、在啟動(dòng)的時(shí)候會(huì)將所有的對(duì)象按順序創(chuàng)建完畢 2罩锐、按需注入 3奉狈、按需獲取
bean參數(shù)詳解
- id:對(duì)象的名字
- destory-method:ioc容器摧毀時(shí)創(chuàng)建
- init-method:創(chuàng)建對(duì)象時(shí)執(zhí)行的方法
- depends-on:創(chuàng)建對(duì)象之前應(yīng)該創(chuàng)建好的對(duì)象
- lazy-init:延遲創(chuàng)建對(duì)象
- scope:設(shè)置作用域:singleton prototype request sesssion global
- session factory-method:工廠方法 factory-bean:工廠對(duì)象
- abstract:標(biāo)記為抽象類
注解創(chuàng)建對(duì)象
1、創(chuàng)建對(duì)象的注解
@Component
@Service
@Repository
@Controller
2涩惑、用法:
//創(chuàng)建對(duì)象的時(shí)候可以使用參數(shù),設(shè)置對(duì)象的引用變量
//如果沒(méi)有寫桑驱,那么默認(rèn)使用小駝峰命名
@Component("blackBox")
public class BlackBox{
}
3.注意:四者用法一致,一般使用@Service
注解注入對(duì)象
1竭恬、注入對(duì)象的注解
- @Resource
- @Autowired
2、用法:
//name:按照名稱來(lái)查找
@Resource(name="blackBox")
private IBox box;
//type:按照類型來(lái)查找
@Resource(type=A4Paper.class)
private IPaper paper;
//如果沒(méi)有寫熬的,那么name就是參數(shù)的變量名 box,所以找不到痊硕,然后按照type來(lái)查找,IBox類型押框,所以可以找得到
//如果沒(méi)有寫岔绸,而內(nèi)存中有多個(gè)相同類型的對(duì)象,那么就報(bào)錯(cuò)
@Resource
private IBox box1;
//@Autowired不能寫任何參數(shù)
//按照類型來(lái)查找橡伞,如果內(nèi)存中有多個(gè)相同類型的對(duì)象盒揉,那么報(bào)錯(cuò)
//解決問(wèn)題:使用@Qualifier來(lái)指定注入哪個(gè)名稱的對(duì)象
@Autowired
@Qualifier("blackBox")
private IBox box;
@Autowired
private IPaper paper;
注意:用哪個(gè)注解根據(jù)實(shí)際需求選擇