Spring IoC反转控制的快速入门

* 下载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、编写反转控制 入门程序

复制代码
 1   public interface IHelloService {
 2       public void sayHello();
 3   }
 4   
 5   public class HelloService implements IHelloService{
 6       public void sayHello(){
 7           System.out.println("hello Spring!");
 8      }
 9  }
10 
11  public class HelloTest {
12      public static void main(String[] args) {
13  
14          // 1、调用HelloService
15          IHelloService helloService1 = new HelloService();// 紧密耦合
16          helloService1.sayHello();
17  
18          // 2、spring内部提供工厂,只需要将实现类进行配置,交由Spring工厂创建对象
19          // 读取 Spring配置文件
20          ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
21                  "applicationContext.xml");
22  
23          // applicationContext就是工厂
24          // 通过配置bean的id获得class类实例
25          IHelloService helloService2 = (IHelloService) applicationContext
26                  .getBean("helloService");
27          
28          helloService2.sayHello();
29      }
30  }
复制代码
复制代码
复制代码
 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        xsi:schemaLocation="
 5 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 6     <!-- 配置IHelloService 实现类Helloservice -->
 7         <!-- 
 8             为cn.itcast.spring.quickstart.HelloService定义id,通过id获得实现类完整类名,通过反射构造对象
 9          -->
10     <bean id="helloService" class="cn.itcast.spring.quickstart.HelloService"></bean>
11 
12 </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 依赖注入),必须要先理解什么是依赖 (一个对象,可以依赖另一个对象,依赖表现在 方法参数上 )

复制代码
 1 class A {
 2 
 3       void setName(String name){// 就可以说 A 对象 依赖 String 类型参数
 4 
 5     }
 6 
 7       void setB(B b){// 就可以说 A 对象 依赖 B 类型参数
 8 
 9       }
10 
11 }
复制代码

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

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

原文地址:https://www.cnblogs.com/bluedy1229/p/3604479.html