spring IOC 简单理解与使用

spring IOC 是一个管理Bean对象生命周期的容器,spring IOC容器对Bean的管理分为几个过程:

1、通过构造器或工厂方法创建bean的实例

2、为bean设置属性值以及对其他bean的引用

3、调用bean的初始化方法

4、bean可以被IOC 容器提供给其他需要的操作

5、IOC容器关闭时,调用bean的销毁方法

 

通过new ClassPathXmlApplicationContext(String configLocation) 的方式创建spring IOC容器的大致过程代码如下:

/**
	 * Create a new ClassPathXmlApplicationContext, loading the definitions
	 * from the given XML file and automatically refreshing the context.
	 * @param configLocation resource location
	 * @throws BeansException if context creation failed
	 */
	public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
		this(new String[] {configLocation}, true, null);
	}

configLocation 表示xml配置文件的位置

public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			refresh();
		}
	}

refresh()是创建IOC容器的核心方法

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

refresh()完成了创建beanFactory、注入beanFactory ,完成beanFactory 初始化等一系列操作,最终使得IOC达到可以向外界提供bean的功能

 

spring环境所需jar包

 

配置xml文件(应用上下文)

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

               http://www.springframework.org/schema/beans/spring-beans.xsd

               http://www.springframework.org/schema/context

               http://www.springframework.org/schema/context/spring-context.xsd ">

 

</beans>

 

通过 bean 节点来配置 bean

<bean id="" class="" init-method="" destroy-method="" lazy-init="" scope="">
		<constructor-arg name="" ref="" value=""></constructor-arg>
		<property name="" ref="" value=""></property>
	</bean>

说明:

1、id 值在 IOC 容器中必须是唯一的,若 id 没有指定,Spring 自动将定性类名作为 Bean 的名字 

2、class属性值为类全名

3、设置 init-method destroy-method 属性, Bean 指定初始化和销毁方法

4、lazy-init=“true”来延迟初始化bean

5、scope 属性设置 Bean 的作用域:

 

作用域

说明

Singleton

Spring IoC容器中一个bean定义只有一个对象实例。默认情况下会在容器启动时初始化bean,但我们可以指定Bean节点的lazy-init=“true”来延迟初始化bean,这时候,只有第一次获取bean会才初始化bean

Prototype

每次从容器获取bean都是新的对象。

Request

每次HTTP请求都会创建一个新的Bean,该作用域只适用于WebApplicationContext环境。

Session

类似Request,每次有新的会话都会创建一个新的Bean,该作用域只适用于WebApplicationContext环境。

6、构造器注入在 <constructor-arg> 元素里声明属性,ref=''''是对引用数据类型的引用,value=""是用来给bean赋值

7、属性注入使用 <property> 元素, 使用 name 属性指定 Bean 的属性名称,value 属性或 <value> 子节点指定属性值

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值