今天回头看了下Spring framework 的ioc 部分,感觉对其理解更深了一步。
首先spring 框架的ioc功能其实就是一个全局的map
可以用来存放需要的对象,而spring框架可以可以自己生成对象放入这个map中,当然你需要通过规定的描述来告诉spring框架如何生成对象,这其中包括两部份:对象和关系。即用到哪些对象,对象间的关系 。
经过这个操作所有的对象都可以通过map获取,当然需要提前获取此map对象即spring的容器对象。
而注解和xml方式的区别在于向spring 容器描述的方式不同。今天先记录下XML的方式。
对于一个java项目来说,所有外部功能的添加,都可以概括为三步:1.添加jar包,2.创建编辑配置文件,3.使用功能
我使用myeclipse提供的强大的功能集成,直接添加spring功能。(作为记录,尽可能的详细一些)
右键——》myeclipse ——》添加spring 能力 或者 安装Spring FACT
这个操作实际上是完成了前两步,自动添加了jar包,创建了配置文件,我们可以直接使用功能了。
在spring中对象都是Bean,你需要做的是在配置文件applicationcontext.xml 中进行对象的描述,在这个配置文件中根节点
为beans 所以他的下面就是又来存放bean的。bean标签有很多属性,通常用到的是id 和class ,id是bean的唯一标识,class则是为这个bean指定对应的对象类。bean标签的下层为property,对应的java类的属性,或者说变量,常用的是name 对应属性名,ref为调用的其他bean,value为属性值。在property下层还可以增加很多子标签,例如集合等。下面贴代码
<?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-3.1.xsd">
<bean id="person" class="com.xufenglai.model.Person">
<property name="body" ref="body"></property>
<property name="behaviors">
<array>
<bean class = "com.xufenglai.model.Behavior"></bean>
<bean class = "com.xufenglai.model.Behavior"></bean>
<bean class = "com.xufenglai.model.Behavior"></bean>
<bean class = "com.xufenglai.model.Behavior"></bean>
</array>
</property>
</bean>
<bean id = "body" class="com.xufenglai.model.Body"></bean>
</beans>
当我们需要获取对象的时候,需要获取spring容器,然后通过容器获取对象。
package com.xufenglai.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xufenglai.model.Person;
public class TestPerson {
@Test
public void testDescription(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = ac.getBean(Person.class);
person.description();
}
}
简单应用到此为止。需要注意的是如果描述对象的过程中使用了property标签,那么你的java类需要有get和set方法,因为这里描述关系的时候使用到了set方法注入(property标签)。
关于依赖注入的后面暂时先不写了。