控制反转(IOC)就是将new出实例化对象的任务从程序员转交给Spring来完成,IOC最大的作用是解耦,解除了对象管理与程序员之间的耦合
一:创建pojo。
1:在src目录下新建包:pojo。
2:在pojo包下新建pojo类:People
package pojo;
public class People {
int id;
String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public People() {
super();
}
public People(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return id+"-->"+name;
}
}
3:在pojo包下新建工厂类:PeopleFactory
package pojo;
public class PeopleFactory {
public People newInstance() {
return new People(123,"李四");
}
public static People newInstance1()
{
return new People(123,"王五");
}
}
二:配置Spring
在src目录下新建文件:applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- id 表示获取到对象标识
class 创建哪个类的对象
-->
<!-- 利用无参构造方法创建对象 -->
<bean id="peo1" class="pojo.People"></bean>
<!-- 利用有参构造方法创建对象 -->
<bean id="peo2" class="pojo.People">
<constructor-arg index="0" name="id" type="int" value="123"></constructor-arg>
<constructor-arg index="1" name="name" type="java.lang.String" value="张三"></constructor-arg>
</bean>
<!-- 实例工厂创建对象 -->
<bean id="factory" class="pojo.PeopleFactory"></bean>
<bean id="peo3" factory-bean="factory" factory-method="newInstance"></bean>
<!-- 静态工厂创建对象 -->
<bean id="peo4" class="pojo.PeopleFactory" factory-method="newInstance1"></bean>
</beans>
三:测试Spring框架的使用
1:在src目录下新建包:mainTest
2:在mainTest包下新建主类:MainTest
package mainTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.People;
public class MainTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
People people1 = ac.getBean("peo1",People.class);
System.out.println(people1);
System.out.println("--------------------");
People people2=ac.getBean("peo2",People.class);
System.out.println(people2);
System.out.println("--------------------");
People people3=ac.getBean("peo3",People.class);
System.out.println(people3);
System.out.println("--------------------");
People people4=ac.getBean("peo4",People.class);
System.out.println(people4);
}
}
3:运行MainTest,结果如下:
四:scope属性
scope是bean标签的属性,控制单例,多例。scope属性具有以下几个属性值
1:singleton 默认值,单例
2:prototype 多例,每次获取重新实例化
3:request 每次请求重新实例化
4:session 每个会话对象内,对象是时单例的
5:application 在每个application对象内是单例
6:global session spring 推出的一个对象,依赖于spring-webmvc-portlet,类似于session