Spring(二)IOC底层实现原理

IOC原理

  将对象创建交给Spring去管理。

实现IOC的两种方式

  • IOC配置文件的方式

  • IOC注解的方式

IOC底层实现原理

  1. 底层实现使用的技术
    1.1 xml配置文件
    1.2 dom4j解析xml
    1.3 工厂模式
    1.4 反射

Spring的IOC实现过程

  • 导入Jar包

  * 如果做Spring最基本的功能,只需要导入最基本的四个即可。(Beans、Core、Context、SpEL)。
  * 因为Spring没有提供日志功能,所以除了上述jar包之外,还要有输出日志的jar包(commons-logging.jar和log4j.jar)。

  • 创建类,在类中创建方法:创建一个简单的类。

  • 创建Spring配置文件,配置创建类

  * Spring核心配置文件名称和位置不是固定的。 一般为Maven项目中resources下的ApplicationContext.xml。
  * 引入约束。

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	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 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd">
<beans>

  
  * 配置Bean

	<bean id="user" class="com.yl.user">
	
    </bean>
  • 写代码测试创建过程:

      //获取xml对象
      ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
      //通过xml对象获取bean
      User user = (User) context.getBean("user");
      System.out.println(user.toString());
原文地址:https://www.cnblogs.com/esileme/p/7479879.html