一、什么是 IOC
IOC:控制反转,控制权的转移,应用程序本身不负责依赖对象的创建和维护,而是由外部容器负责创建和维护。
扩展:IOC既然是控制反转,到底是那些方面被反转了呢? 即获取依赖对象的过程被反转了,控制被反转之后,获取依赖对象的过程由自身管理变为了IOC容器的主动注入,所谓的依赖注入,就是由IOC容器在运行期间,动态的将某种依赖关系注入到对象之中。
DI(依赖注入)是其中一种实现方式。
IOC的目的:创建对象并组装对象之间的关系。
Spring 的 Bean 配置
<?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-3.0.xsd"> <bean id="helloWorld" class="com.tutorialspoint.HelloWorld"> <property name="message" value="Hello World!"/> </bean> </beans>
Spring 实现 HelloWord:
1、这是 HelloWorld.java
package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } }
2、这是 Main 方法
package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); } }
关于主程序,主要有两点需要注意
1、我们使用框架中的 API ClassPathXmlApplicationContext() 来创建应用程序的上下文。他处理并初始化所有的对象。
2、使用已经创建的上下文的 getBean()方法来获取所需的 bean。这个方法使用 bean 的 ID 返回一个最终可以转换为实际对象的通用对象。
Bean.xml 的加载方式有三种
Spring 的注入是指在启动 Spring 容器加载 bean 配置的时候,完成对变量的赋值工作。
Spring常用的赋值方式:
1、设值注入:调用 set 方法进行赋值
2、构造注入:调用构造函数进行赋值