Spring学习–ioc

By | 2014/08/19

SpringIoc 又称为Spring的控制反转:把对象的创建、初始化、销毁等工作交给spring容器来完成。也就是由spring容器控制对象的生命周期。

  1. 第一个简单的入门例子

配置文件

[code]

<?xml version=<em>"1.0"</em> encoding=<em>"UTF-8"</em>?>

<beans xmlns=<em>"http://www.springframework.org/schema/beans"</em>

xmlns:xsi=<em>"http://www.w3.org/2001/XMLSchema-instance"</em>

xsi:schemaLocation=<em>"http://www.springframework.org/schema/beans</em>

<em>           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"</em>>

<!–

把HelloWorld这个类纳入spring容器

id为bean的唯一标识

正规的写法:

类的第一个字母变成小写,其余不变

class为类的全名

–>

<bean id=<em>"helloWorld"</em> class=<em>"cn.ytu.ioc.HelloWorld"</em>></bean>

<!—

<alias></alias>标签用来为类设置别名,其规则如下:

name与bean中的id对应

alias 名字(别名)

–>

<alias alias="狗蛋" name="helloWorld"/>

<alias alias="王三麻子" name="helloWorld"/>

</beans>

[/code]

HelloWorld.class

[code]
public class HelloWorld {
public void say() {
System.out.println("Hello World!!");
}
}
</code>

[/code]

测试类 IocTest.java

[code]

<strong>import</strong> org.junit.Test;

<strong>import</strong> org.springframework.context.ApplicationContext;

<strong>import</strong> org.springframework.context.support.ClassPathXmlApplicationContext;

&nbsp;

<strong>public</strong><strong>class</strong> IocTest {

/**

* 启动spring容器 ,创建spring容器对象就相当于启动spring容器

*spring容器做的工作:创建对象

*/

@Test

<strong>public</strong><strong>void</strong> testHelloWorld(){

ApplicationContext context = <strong>new</strong> ClassPathXmlApplicationContext("cn/ytu/ioc/applicationContext.xml");

HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");

helloWorld.say();

}

}

[/code]

二.Spring容器内部对象的创建

1. 三种方案

利用默认的构造函数

利用静态工厂方法

利用实例工厂方法

2. 创建对象的时机

默认情况下,在spring启动的时候,创建纳入spring容器中所有的bean。优点是在spring容器启动的时候,可以检查错误。但是如果bean的属性中有数据,会过早的加载到内存中,所以如果bean中有数据,应该把数据的对象的声明放在方法中。

如果在spring的配置文件中,有lazy-init为true,则context.getBean("beanId")时才要创建对象缺点:在spring容器启动的时候,是检验不出错误的

说明:

spring容器默认调用类的默认的构造器来创建对象的

如果在HelloWorld中,没有默认的构造器,则spring在创建helloWorld对象时,会报错因为找不到默认的构造器

三.Spring容器创建对象的作用域

在配置文件中,scope为

"singleton" 单例模式 默认值

spring产生的bean只有一个实例

处于单例模式的bean的创建、初始化、销毁都是受spring容器管理的

在容器关闭的时候执行销毁工作

"prototype" 多例模式

spring容器负责该bean的创建、初始化,但是销毁工作程序员做

无论该bean的lazy-init为什么值,都在执行context.getBean时创建对象

如果该bean中有资源对象,手动关闭

3 thoughts on “Spring学习–ioc

    1. 赵洋 Post author

      知道了,老师,已经修改了。

      Reply
  1. 李 志豪

    其实现在用jetty的好多啊,可以考虑学学jetty。
    还有,nginx是个很好的服务器,既可以做http服务器,也可以做负载均衡服务器,性能很好的。

    Reply

发表评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据