Spring是一个基于IOC和AOP的结构J2EE系统的框架
IOC 反转控制 是Spring的基础,Inversion Of Control
简单说就是创建对象由以前的程序员自己new 构造方法来调用,变成了交由Spring创建对象
DI 依赖注入 Dependency Inject. 简单地说就是拿到的对象的属性,已经被注入好相关值了,直接使用即可。
目标:用Spring获取一个对象,并打印其name。
第一步:新建项目(java project类型)
第二步:下载lib.rar,并解压到 Spring/lib 目录下
第三步:导入包
把jar包导入到项目中,导包办法:右键 project->properties->java build path->libaries->add external jars
第四步:创建Category,用来演示IOC和DI
1 package com.spring.cate; 2 3 public class Category { 4 private int id; 5 private String name; 6 7 public int getId() { 8 return id; 9 } 10 11 public void setId(int id) { 12 this.id = id; 13 } 14 15 public String getName() { 16 return name; 17 } 18 19 public void setName(String name) { 20 this.name = name; 21 } 22 }
第五步:在src目录下新建applicationContext.xml文件
applicationContext.xml是Spring的核心配置文件,通过关键字category即可获取Category对象,该对象获取的时候,即被注入了字符串"category 333“到name属性
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 10 http://www.springframework.org/schema/aop 11 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 12 http://www.springframework.org/schema/tx 13 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 14 http://www.springframework.org/schema/context 15 http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 16 17 <bean name="category" class="com.spring.cate.Category"> 18 <property name="name" value="category 3333" /> 19 </bean> 20 21 </beans>
第六步:测试
测试代码,演示通过spring获取Category对象,以及该对象被注入的name属性。
如图所示,可以打印出通过Spring拿到的Category对象的name属性
1 package com.spring.test; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 import com.spring.cate.Category; 7 8 public class TestSpring { 9 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" }); 13 Category c = (Category) context.getBean("category"); 14 System.out.println(c.getName()); 15 } 16 17 }
总结:
对象的生命周期由Spring来管理,直接从Spring那里去获取一个对象。 IOC是反转控制 (Inversion Of Control)的缩写,就像控制权从本来在自己手里,交给了Spring。
不需要自己再去new对象,直接由Spring生产。对象的属性通过在applicationContext.xml中以注入的方式传递给对象。