您的位置:首页 > 编程语言 > Java开发

02_Spring控制反转案例快速入门

2015-07-24 22:26 495 查看

Spring控制反转案例快速入门

1.下载Spring最新开发包
http://www.springsource.org/download/community 下载spring3.2 的开发包

目录结构(spring-framework-3.2.0.RELEASE)



* docs 存放API和 规范文档

* libs 开发jar包

* schemas 开发过程中需要导入xml的schema 约束



我们还有一个依赖包(spring-framework-3.0.2.RELEASE-dependencies),里面有开发涉及的所有jar包,以后开发可以从这里面找jar包。



2.复制Spring开发 jar包到工程

复制核心容器包含jar包 (beans、core、context、expression language)

spring 的 jar包 需要依赖 commons-logging的 jar (commons-logging 类似 slf4j 是通用日志组件,需要整合 log4j ),拷贝log4j.properties

* 提示:spring3.0.X 版本 asm jar包 已经被合并到 spring core包中

3.理解IoC控制反转和DI依赖注入

IoC Inverse of Control 反转控制的概念,就是将原本在程序中手动创建UserService对象的控制权,交由Spring框架管理,简单说,就是创建UserService对象控制权被反转到了Spring框架

DI:Dependency Injection 依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件



面试题: IoC 和 DI的区别?

IoC 控制反转,指将对象的创建权,反转到Spring容器 , DI 依赖注入,指Spring创建对象的过程中,将对象依赖属性通过配置进行注入

4.编写Spring核心配置文件

在src目录创建 applicationContext.xml

在docs\spring-framework-reference\html 找到 xsd-config.html,在最下方引入bean的约束

<beansxmlns="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">[/code] 
编写配置文件applicationContext.xml

<!-- 配置使用哪个实现类 对  IHelloService 进行实例化-->


<!-- 配置实现类HelloServiceImpl,定义名称helloService-->


<beanid="helloService"class="cn.itcast.spring.a_quickstart.HelloServiceImpl">


<!-- helloService 依赖 info属性  -->
<!-- 通过property配置spring创建 helloService对象时,自动调用 setInfo方法 完成属性注入  -->
<property name="info" value="传智播客"></property>


</bean>


5.在程序中读取Spring配置文件,通过Spring框架获得Bean,完成相应操作

加载classpath(src): new ClassPathXmlApplicationContext("applicationContext.xml");

加载磁盘路径:new FileSystemXmlApplicationContext("applicationContext.xml");

publicstaticvoid main(String[] args){


// 传统写法 (紧密耦合)


HelloServiceImpl helloService =newHelloServiceImpl();


// 手动调用 set 方法为 info 进行赋值
helloService.setInfo("spring");


helloService.sayHello();




// 工厂+反射 +配置文件 ,实例化 IHelloService的对象


ApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext.xml");


// 通过工厂根据配置名称获得实例对象


IHelloService iHelloService2 =(IHelloService) applicationContext.getBean("helloService");


iHelloService2.sayHello();


// 控制反转,对象的创建权被反转到 Spring框架


}


说明:
IHelloService接口定义:

// 接口


publicinterfaceIHelloService{


publicvoid sayHello();


}


HelloServiceImpl实现类定义:

// 实现类


publicclassHelloServiceImplimplementsIHelloService{


private String info;


publicvoid sayHello(){


System.out.println("hello,"+info);


}


// HelloServiceImpl 的实例 依赖 String 类型 info 数据
// UML OOD设计中 依赖强调 方法中参数
public void setInfo(String info) {
this.info = info;
}


}




来自为知笔记(Wiz)



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: