【Spring】之 IOC初识


一、问题


(1)什么是 IOC?

控制反转(Inversion of Control,IOC),又称 “依赖注入”(Dependency Lookup)。

  1. 通过控制反转,对象创建和传递交由 IOC 容器。
  2. 有对象引用,则可依赖注入。

所谓IOC容器就是指的 SpringBean工厂里面的 Map存储结构(存储了Bean的实例)。


(2)为什么要用 IOC?

可以用来降低计算机代码之间的耦合度。

更好的管理对象本身,对象和对象之间的关系。

优点:

  1. 管理类的创建、销毁
  2. 类与类之间的依赖关系(比如:循环依赖等等)
  3. 规避对象创建不规范,不一致
  4. 解耦合
  5. 让开发者更关注业务开发

(3)怎么创建 IOC?

Spring IOC 容器加载Bean方式有:XML配置方式 和 注解方式


1. XML配置方式

通过 bean标签

public class Application {

    public static void main(String[] args) {

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        Car car = (Car) applicationContext.getBean("car");
        
        Car car2 = (Car) applicationContext.getBean(Car.class);

     }
}

2. 注解方式

  1. 在对应需要的类上加上注解。

@Component @Controller @Service Repository等等

  1. 配置包扫描依赖
    context:component-scan

扫描对应包下的注解,将注解的类加载进 IOC 容器

注解方式,示例代码:

@ComponentScan(basePackages = "com.donaldy")
public class Application {

    public static void main(String[] args) {

        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Application.class);

        Car car = (Car) applicationContext.getBean("car");

     }
}

(4)IOC 容器是如何初始化 Bean 实例的?

如图:
在这里插入图片描述



二、一些概念


先了解一些概念和其名字所代表的意思。

(1)BeanFactory

beanFactory: bean 工厂

生产bean


(2)ApplicationContext

applicationContext: 应用上下文

总览全局


(2)BeanDefinition

definition:定义

即每个bean都有自己定义的信息:属性、类名、类型等等

反应对象之间的互相依赖关系

发布了404 篇原创文章 · 获赞 270 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/fanfan4569/article/details/101910307