2016/1/16 10:38:54
- bean的配置項
- bean的作用域
- bean的生命週期
- bean的自動裝配
- Resources&ResourceLoader
1.bean的配置項(常用)
- Id:整個IOC容器中bean的唯一標識
- Class:具體要實例化的類
- Scope:是單例還是多例
- Constructor arguments:構造參數
- Properties:成員變量
- Autowiring mode:自動裝配模式
- lazy—initialization mode:懶加載模式
- Initialization/destruction method:初始化和銷燬的方法
2.bean的作用域
- singleton(默認模式):單例,指一個bean容器中只存在一份
- prototype:每次請求(每次使用)創建新的實例,destroy方式不生效
- request:每次http請求創建一個實例且僅在當前request內有效
- session:同上,每次http請求創建,當前session中有效
- global session:基於portlet的web中有效(portlet定義了global sessio),如果在web中,同session
Scope測試
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean id="beanScope" class="com.zjx.bean.BeanScope"></bean>
</beans>
bean類
package com.zjx.bean;
public class BeanScope {
public void say(){
// 哈希碼是bean的唯一標識
System.out.println("BeanScope say:"+this.hashCode());
}
}
測試類
package com.zjx.interfaces.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.zjx.bean.BeanScope;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanScope extends UnitTestBase {
public TestBeanScope() {
super("classpath*:spring-beanScope.xml");
}
@Test
public void test(){
BeanScope bean = super.getBean("beanScope");
bean.say();
bean = super.getBean("beanScope");
bean.say();
}
}
控制檯兩次打印的哈希碼一致,說明該實體類實例對象是一個;如果將XML配置文件中的scope設置爲prototype,則兩次得到的哈希碼不一致,說明不是同一個實例