学习目的:使用spring获取一个对象,并打印名字
Part 1
新建一个Java project,命名为spring。
Part 2
导入spring框架所需要的jar包。
在spring项目文件夹内新建一个lib文件夹,用来存放spring所需jar包。
右键项目:spring->properties->java build path->libaries->add external jars
Part 3
新建一个pojo类:Category
package cn.vaefun.pojo;
public class Category {
private int id;
private 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;
}
}
Part 4
在src下新建一个application.xml。
配置一个bean,名字为c,class完整类名为上面pojo类Category的完整类名,并配置其name属性的value为category 1。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="Index of /schema/aop"
xmlns:tx="Index of /schema/tx"
xmlns:context="Index of /schema/context"
xsi:schemaLocation="
Index of /schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Index of /schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
Index of /schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
Index of /schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean name="c" class="cn.vaefun.pojo.Category">
<property name="name" value="category 1" />
</bean>
</beans>
Part 5
新建一个TestSpring类。
package cn.vaefun.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.vaefun.pojo.Category;
public class TestSpring {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Category category = (Category)context.getBean("c");
System.out.println(category.getName());
}
}
Part 6
运行成功,通过spring获取到一个Category对象,并输出其name:category 1,学习目的完成。
Part 7
总结(以获取对象方式为例)
传统的方式:
通过new 关键字主动创建一个对象
IOC方式:
对象的生命周期由Spring来管理,直接从Spring那里去获取一个对象。 IOC是 反转控制 (Inversion Of Control)的缩写,就像控制权从本来在自己手里,交给了Spring。
打个比喻:
传统方式:相当于你自己去菜市场new 了一只鸡,不过是生鸡,要自己拔毛,去内脏,再上花椒,酱油,烤制,经过各种工序之后,才可以食用。
用 IOC:相当于去馆子(Spring)点了一只鸡,交到你手上的时候,已经五味俱全,你就只管吃就行了。