IOC和DI简介
IoC:Inverse of Control(控制反转):
读作“反转控制”,更好理解,不是什么技术,而是一种设计思想,好比于MVC。就是将原本在程序中手动创建对象的控制权,交由Spring框架来管理。
正控:若调用者需要使用某个对象,其自身就得负责该对象的创建。
反控:调用者只管负责从Spring容器中获取需要使用的对象,不关心对象的创建过程,也就是把创建对象的控制权反转给了Spring框架。
在这里完美地体现了好莱坞法则(Don’t call me ,I’ll call you)。
DI:Dependency Injection(依赖注入)
从字面上分析:
IoC:指将对象的创建权,反转给了Spring容器;
DI :指Spring创建对象的过程中,将对象依赖属性(简单值,集合,对象)通过配置设值给该对象。
IoC和DI其实是同一个概念的不同角度描述,DI相对IoC而言,明确描述了“被注入对象依赖IoC容器配置依赖对象”。
Container:容器,在生活中容器就是一种盛放东西的器皿,从程序设计角度看作是装对象的对象,因为存在对对象的存入、取出等操作,所以容器还要管理对象的生命周期。
第一个Hello World
步骤:
1.准备jar包
2.开发HelloWorld程序
3.在applicationContext.xml中完成配置(xsd-config.html)
4.启动容器
5.从容器中得到bean
6.调用bean响应的方法
----------------------------------------------------------------------
package com._520it.spring.hello.HelloWorld public class HelloWorld { public void sayHello(){ System.out.println("你好 Spring"); } }
<?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"> <bean id="hello" class="com._520it.spring.hello.HelloWorld" /> </beans>
@Test public void testHelloWorld() throws Exception { //1:加载资源 Resource resource = new ClassPathResource("applicationContext.xml"); //2:创建Spring容器对象 BeanFactory factory = new XmlBeanFactory(resource); //3:从Spring容器中获取hello的bean对象 HelloWorld world = (HelloWorld) factory.getBean("hello"); world.sayHello(); }
//修改HelloWord代码 public class HelloWorld { private String name; public void setName(String name) { this.name = name; } public void sayHello() { System.out.println("你好" + name); } }
<!-- xml配置 -->
<bean id="helloWorld" class="com._520it.day1._01_hello.HelloWorld"> <property name="name" value="Will"/> </bean>
需要的jar包:
spring-beans-4.1.2.RELEASE.jar
spring-core-4.1.2.RELEASE.jar
报错再添加:
com.springsource.org.apache.commons.logging-1.1.1.jar