Spring介绍
框架:高度抽取可重用代码的一种设计;高度的通用性;
多个可重用模块的集合,形成某个领域的整体解决方案
Spring框架:容器:可以管理所有的组件;IOC和AOP
IOC(容器):Iversion Of Control 控制反转
用容器来整合框架
控制:资源的获取
- 主动式(自己用什么资源就创建new)
- 被动式(资源的获取交给容器创建和设置)
容器:从主动的new资源为被动的接受资源
DI(Dependency Injection):依赖注入(是IOC思想的具体实现)。容器能知道那个组件运行的时候,需要另一个组件,容器通过反射的形式,将容器中的准备好的对象注入(利用反射给属性赋值)到最初的那个组件中。
容器中对象的创建在容器创建的时候就创建了。
一个bean对应一个对象
同一个组件在ioc中是单例的。
javabean的属性名是由getter/setter方法决定的,去掉set之后将首字母小写之后得到的字符串就是属性名。
配置文件:
bean的创建原理
bean的创建就是框架利用反射new出来的bean实例
话说反射是一种效率很低的方法,所以有哪些对象是应该使用bean来创建的呢?
<?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="stu1" class="com.onezero.Student">
<property name="name" value="张三"></property>
<property name="age" value="18"></property>
</bean>
<bean id="stu2" class="com.onezero.Student">
<property name="name" value="李四"></property>
<property name="age" value="19"></property>
</bean>
<bean id="stu3" class="com.onezero.Student">
<constructor-arg name="age" value="20"></constructor-arg>
<constructor-arg name="name" value="onezero"></constructor-arg>
</bean>
<bean id="stu4" class="com.onezero.Student">
<constructor-arg value="马云"></constructor-arg>
<constructor-arg value="40"></constructor-arg>
</bean>
</beans>
在配置文件中使用property标签是通过set方法来赋值的。通过constructor-arg可以调用有参构造器赋值。若是严格按照有参构造器中参数出现的顺序写属性,则可以省略name。
若没有严格按照构造器中给出的参数数据赋值,可以通过index指定赋给第几个参数。
若是构造器进行了重载且参数个数一样,如果想省略name需要指定type(即参数类型)
综上所述,不省略name是一种比较常见的配置方法。
通过p命名空间为bean赋值
通过get/set方法进行赋值
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="stu05" class="com.onezero.Student" p:age="19" p:name