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:spring-beanScope.xml
<?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,则两次得到的哈希码不一致,说明不是同一个实例
Spring Bean 配置与作用域详解
本文深入探讨 Spring 框架中 bean 的配置项、作用域、生命周期及自动装配,通过 XML 示例展示了不同作用域(如 singleton、prototype 等)的实现,并通过代码测试验证了实例化过程。
1238

被折叠的 条评论
为什么被折叠?



