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

Spring IoC反转控制的快速入门

2014-03-17 09:45 441 查看
* 下载Spring最新开发包

* 复制Spring开发jar包到工程

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

* 编写Spring核心配置文件

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

本总结是按照版本3.2.2 进行总结的,---下载dist开发包

一、IoC反转控制 快速入门

1、下载开发包

Spring解压目录

  docs 文档(规范和javadoc)

  libs jar包

  schema 开发过程中配置文件需要导入约束

2、将开发jar包导入到 web project



3、编写反转控制 入门程序



public interface IHelloService {
public void sayHello();
}

public class HelloService implements IHelloService{
public void sayHello(){
System.out.println("hello Spring!");
}
}

public class HelloTest {
public static void main(String[] args) {

// 1、调用HelloService
IHelloService helloService1 = new HelloService();// 紧密耦合
helloService1.sayHello();

// 2、spring内部提供工厂,只需要将实现类进行配置,交由Spring工厂创建对象
// 读取 Spring配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");

// applicationContext就是工厂
// 通过配置bean的id获得class类实例
IHelloService helloService2 = (IHelloService) applicationContext
.getBean("helloService");

helloService2.sayHello();
}
}









<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">
<!-- 配置IHelloService 实现类Helloservice -->
<!--
为cn.itcast.spring.quickstart.HelloService定义id,通过id获得实现类完整类名,通过反射构造对象
-->
<bean id="helloService" class="cn.itcast.spring.quickstart.HelloService"></bean>

</beans>







上面代码可以得出:

HelloTest类中使用 HelloService 类对象

传统方法: IHelloService helloservcie = new HelloService();

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

IOC的思想:

程序中通过id获得Bean实例;

使用了Spring,就相当于 使用了一个大的工厂,将原来程序中对象的创建,交给Spring提供的工厂来完成。

(原来在程序中自己new一个对象,现在让spring把对象提供给你,由你自己new对象,到spring把对象提供给你,你的对象的创建权被反转了。)

二、依赖注入

DI(Dependency Injection)依赖注入

DI的好处,如果需要向一个Bean中注入 另一个Bean时,多个Bean都要交给Spring管理,注入比较方便,

     如果不进行配置注入,需要手懂注入。

一个对象,可以依赖另一个对象,依赖表现在 方法参数上

理解DI(Dependency Injection 依赖注入),必须要先理解什么是依赖 (一个对象,可以依赖另一个对象,依赖表现在 方法参数上 )



class A {

void setName(String name){// 就可以说 A 对象 依赖 String 类型参数

}

void setB(B b){// 就可以说 A 对象 依赖 B 类型参数

}

}




* 依赖与成员变量无关,只和方法有关

* 使用Spring Ioc 将对象 创建权交给Spring, Spring在创建对象时,将依赖对象注入给目标对象

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