05 Spring IOC 容器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hxdeng/article/details/82904343

1. Spring IOC 容器

IOC(Inversion of Control) 控制权的转移,应用程序本身不负责依赖的创建和维护,而由外部容器创建和维护 Spring IOC作用:专门负责对象的创建和依赖的管理注入

DI(Dependency Injection) 是一种IOC实现方式
DI 目的:创建对象并且组装对象之间的关系

2004年,Martin Fowler 探讨了一个问题,既然IOC是控制反转,那么到底是“哪些方面的控制被反转了呢?”,经过详细地分析和论证后,他得出了答案:“获取依赖对象的过程被反转了”。控制反转之后,获得依赖对象的过程由自身管理变为了IOC主动注入。于是,他给“控制反转”取了一个更合适的名字叫做“依赖注入(Dependency Injection)”。他的这个答案实际上给出了实现IOC的方法:注入。所谓依赖注入,就是有IOC容器在运行期间,动态地将某个依赖关系注入到对象中。

比如生活中以前吃饭需要自己做,现在吃饭交给美团负责,我们只需要下单即可。比如租房我们需要自己找,现在交给58就好。

2. Spring IOC 容器中如何管理对象

想让Bean让IOC管理需要在IOC中配置即可,而Spring IOC中Bean配置有两种:

  1. xml配置
  2. 注解配置

配置文件配置

<?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="exampleBean" class="com.javaee.ExampleBean">
	</bean>
</beans>

注解

@Service 等注解

3. Spring Bean 容器初始化

Spring IOC 容器中配置好Bean后如何获取Bean对象?Spring Bean容器中获取Bean对象有如下方式:

  1. 文件方式
  2. Classpath 方式
  3. WEB方式

文件方式

FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("F:/spring.xml");

Classpath方式

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");

WEB方式
WEB 方式适用于WEB项目,需要在web.xml文件中配置即可

<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:spring.xml</param-value>
</context-param>

4. Spring 注入

Spring 注入是指在启动Spring 容器加载Bean配置的时候,完成对变量赋值行为。Spring注入分两种注入方式;

  1. 设值注入(属性注入)
  2. 构造注入
  3. 工厂方法注入

4.1 属性注入


<bean id="productService" class="com.javaee.spring.service.ProductService">
    <!-- name 当前类中需要提供一个setXxxx方法  -->
    <!-- ref 引入其他bean的Id -->
    <property name="productDao" ref="productDao" />
</bean>

<bean id="productDao" class="com.javaee.spring.dao.ProductDao">
    
</bean>

4.2 构造注入

<bean id="productService" class="com.javaee.spring.service.ProductService">
    <constructor-arg name="productDao" ref="productDao" />
</bean>

<bean id="productDao" class="com.javaee.spring.dao.ProductDao">
    
</bean>

注意
构造方法注入必须提提供对应参数的构造方法

猜你喜欢

转载自blog.csdn.net/hxdeng/article/details/82904343