专栏首页CoffeeLandSpring IOC的理解
原创

Spring IOC的理解

Table of Content

  • What is the IoC/DI?
  • How to understand IoC/DI?
  • How spring did the bean creation?
  • how Spring use DI to find the Beans?

What is the IoC/DI?

Sping IoC is Inversion of Control. 控制反转.

Spring DI 是 Dependency Injection 依赖注入.

它是user把创建对象的控制权交给了spring container.

这样做的好处就是可以Decoupling解耦.

控制反转是Spring 的一种设计思想, 使用的途径就是依赖注入

How to understand IoC/DI?

public class Car
{
    private Wheel wheel = new Wheel();
}

public class Wheel
{
    private float size;
}          

publicclassCar{private Wheel wheel;publicCar(Wheel wheel){this.wheel = wheel;}}publicclassWheel{private float size;}

使用IoC/DI来创建对象

public class Car
{
    private Wheel wheel;
    
    // 这样做的好处就是能够解耦, 并且方便开发者能够用mock测试
    public Car(Wheel wheel)
    {
        this.wheel = wheel;
    }
}

public class Wheel
{
    private float size;
}   

Spring IoC container

spring IoC 容器创建对象, 组装,配置, 管理bean的生命周期从创建到销毁.

spring容器使用DI来管理application的组件

How spring did the bean creation?

  • How to create a bean
  • Bean's lifecycle details
  • Bean's dependencies

How to create a bean

1.Create a metadata object

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. Create Bean Configuration File

<?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>

3. Create bean

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();
   }
}

4. Run program

Your Message : Hello World!

ClassPathXmlApplicationContext().This API loads beans configuration file and eventually based on the provided API, it takes care of creating and initializing all the objects

ClassPathXmlApplicationContext在程序运行时会加载bean的xml配置文件,来创建bean和初始化

Bean's lifecycle details

Spring bean factory is responsible for managing the life cycle of beans created through spring container

Spring framework provides following 4 ways for controlling life cycle events of a bean:

  1. InitializingBean and DisposableBean callback interfaces
  2. *Aware interfaces for specific behavior
  3. Custom init() and destroy() methods in bean configuration file
  4. @PostConstruct and @PreDestroy annotations

how Spring use DI to find the Beans?

使用反射

public static Object newInstance(String className) {
		Class<?> cls = null;
		Object obj = null;
		try {
			cls = Class.forName(className);
			obj = cls.newInstance();
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		return obj;
}

Refers

https://www.tutorialspoint.com/spring/spring_bean_life_cycle.htm

https://howtodoinjava.com/spring-core/spring-bean-life-cycle/

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • springboot 1.5.20.RELEASE可能会将http请求变成https

    系统的有一个写log的微服务A, spring boot的version是2.1.5.RELEASE

    CoffeeLand
  • Springframwork.Util之StopWatch 多任务计时

    StopWatch是spring框架提供的一个util, 用来做多任务的计时, 隐藏了System.currentTimeMillis()的使用, 增加应用程序...

    CoffeeLand
  • Fortinet面试总结

    https://stackoverflow.com/questions/29225745/where-is-the-local-final-variable-i...

    CoffeeLand
  • Java设计模式-装饰者模式

    装饰者模式:在不改变原类文件以及不使用继承的情况下,动态地将责任附加到对象上,从而实现动态拓展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对...

    蒋老湿
  • GEF入门实例_总结_05_显示一个空白编辑器

    在第三节( GEF入门实例_总结_03_显示菜单和工具栏  ),我们创建了菜单和工具栏。

    shirayner
  • Eclipse插件开发_学习_02_GEF入门实例

    (2)搜索 editors,选择 org.eclipse.ui.editors  扩展点,finish

    shirayner
  • 使用apache的httpClient对异步网络请求进行封装

    Meet相识
  • 你想过吗,为什么说面向对象最符合人的思维?

    在学习Java的过程中,我觉得面向对象是我遇到的第二个难题(第一个就是配置环境变量,哈哈)。我相信也有很多同胞也在这里被绊脚了吧,今天的话也就是其实也只是作为笔...

    ZackSock
  • 消息队列:快速上手ActiveMQ消息队列的JMS方式使用(两种模式:Topic和Queue的消息推送和订阅)

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 ...

    eguid
  • Netty 如何实现心跳机制与断线重连?

    所谓心跳, 即在 TCP 长连接中, 客户端和服务器之间定期发送的一种特殊的数据包, 通知对方自己还在线, 以确保 TCP 连接的有效性.

    Java技术栈

扫码关注云+社区

领取腾讯云代金券