官网:www.spring.io
开源软件下载网站:mirror.bit.edu.cn
类的创建模式
1. new关键字创建
2. 工厂创建对象(factory:封装,用方法的模式创建对象)
3. 容器创建对象(container)
Spring 搭建步骤
1. 新建maven项目
2. Pom.xml添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
</dependencies>
3. xml文件模板
1.从doc文件复制模板文件
<?xml version="1.0" encoding="UTF-8"?>
<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">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
2.myeclipse快捷生成xml文件
file-myeclipse-addspring capabilities
然后更改spring-bean-版本号。
Xml文件操作:
当<alt+/无提示时,可以将本地xsd文件关联到eclipse中:windows-preference-xml-xmlcatalog-add-file system选中本地xsd文件地址, key type:schema location
Key:当前xml配的远程xsd地址。
在spring的ioc容器中配置bean:
<bean id = “引用名” class = “类名(带包名)”>
<property name="id"value="1001"></property>
属性注入
property标签实际调用 setName指定名字首字母大小的方法
value只适合基本数据类型 数字 字符 日期
ref表示对象的引用
构造器注入
<constructor-arg index=”0”value="1"></constructor-arg>
通过索引传入构造器参数,索引从0开始
<constructor-argname="id" value="1"></constructor-arg>
通过属性名传入构造器参数
<constructor-arg type="java.lang.String"value="aab"></constructor-arg>
通过属性类型传入构造器参数
一般用属性名来注入
</bean>
<!-- 自动装配 将当前实例中所有的对象属性 全部进行填充
byType对象属性所在的类 在容器中 只能拥有一个实例
多个实例是相对的 如果b中是个集合 可以装配多个A
byName根据当前对象属性的名称来查找对应的实例
-->
<bean id="b" class="cn.et.lesson01.autowire.B"autowire="byType" >
</bean>
单例和多例
<bean id="a" class="cn.et.lesson01.prototype.A"scope="singleton"></bean>
spring中bean默认都是单实例 scope="singleton"
singleton 单例 默认值
容器初始化时(ApplicationContext context =newGenericXmlApplicationContext("classpath:/cn/et/lesson01/prototype/spring.xml");
实例化
prototype 多例
getBean对象 实例化
在容器中取出实例化对象:
获取容器:
ApplicationContext context = newGenericXmlApplicationContext("classpath:/cn/et/lesson01/hello/spring.xml");
FileSystemXmlApplicationContext从文件系统寻找xml文件 带盘符
ClassPathXmlApplicationContext 从类路径下寻找 常用 建议使用
GenericXmlApplicationContext 通用 默认查找类路径
WebApplicationContext web.xml中实例化
就近原则 所有ApplicationContext指令 都支持 字符串定义查找方式
classpath:
file:
获取实例化对象:
Getbean(“”)方法获取
参数可传:
引用名,可取多个同类型的实例
类名.class,只能取单实例的类的实例
(如果没有指定id的类 默认的名字 是 类名#编号)