Spring学习1--基本概念
来源:互联网 发布:软件开发逻辑架构 编辑:程序博客网 时间:2024/06/05 04:31
为什么要用Spring?
Spring的本质是管理软件中的对象,如何创建对象和维护对象之间的关系。
什么是IOC?
指程序中获取对象的方式发生了反转,由最初的new方式创建,转变为由第三方框架创建。
什么是Bean?
就是一种规范并且简单的java对象。
当需要管理javaBean对象的时候就要用Spring,Spring是最简洁的对象管理方案
容器和Bean管理
1.Spring容器的实例化:
//加载src下的applicationContext.xml文件对容器实例化 String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
2.Bean的实例化(3种方式):
将对象的创建规则告诉Spring,Spring会帮我们创建对象
用构造器来实例化
<!--applicationContext.xml配置:--> <bean id="指定Bean名称" class="指定Bean的类型"></bean>
这种方法会自动调用无参构造器创建对象,因此该实体类必须有无参构造器
java代码:
public void instanceSpring(){ //加载spring配置文件 String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf) //调用getBean方法取得被实例化的对象。 指定Bean的类型 实例名 = (指定Bean的类型) ac.getBean("指定Bean名称"); }
- 使用静态工厂方法实例化
- 使用实例工厂方法实例化
2,3的链接在下面
http://glzaction.iteye.com/blog/1286325
3.Bean的 作用域和销毁方法
作用域:
- singleton
容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。 - prototype
Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例。 - request
即每次HTTP请求将会有各自的bean实例, 它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。 - session
在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web有效。 - global Session
在一个全局的HTTP Session中,一个bean定义对应一个实例。
销毁方法:
在bean中可以指定销毁方法:
<bean id="test" destory-method="destory">
这样Spring会自动寻找test类中的destory方法
4.Bean的延迟实例化:
ApplicationContext实现的额默认模式是在启动时将所有的singleton Bean提前进行实例化,如果不想让一个singleton Bean提前实例化可以用如下方法:
<bean id="exampleBean" lazy-init="true" class="com.test" />
5.指定Bean的依赖关系:
<bean id="beanOne" class="ExampleBean" depends-on="beadTwo,beanThree,..." /><bean id="beanTwo" class="SecondBean" /><bean id="beanThree" class="ThreeBean" />
0 0
- Spring学习1--基本概念
- spring IoC学习 ------IoC基本概念
- Spring入门1-基本概念
- spring学习笔记(9)AOP基本概念
- Spring学习(2):SpringAOP基本概念详解
- 慕课网学习spring入门篇-AOP基本概念
- rpc学习1-基本概念
- (1) ebj学习:基本概念
- 机器学习基本概念-1
- 机器学习-1-基本概念
- Spring基本概念
- Spring基本概念
- Spring基本概念
- spring基本概念
- spring基本概念
- [XML学习笔记][1]基本概念
- pomelo学习笔记 (1)基本概念
- Java学习(1) java基本概念
- android即时消息处理机制
- 近期面试遇到的问题以及总结(python和openstack)
- Android按比例布局之layout_weight和weightSum的使用
- Eclipse几个版本号的区别
- 工程师创业要点
- Spring学习1--基本概念
- android中像素单位dp、px、pt、sp的比较
- Android Studio 简介及导入 jar 包和第三方开源库方法
- VBS教程:创建txt文件
- easyui datebox 清空值或添加自定义按钮
- leetcode 257 : Binary Tree Paths
- web认证机制
- android--(http协议、显示网络中的图片、https)
- Word文档打不开怎么办