小白入门spring——IOC

    科技2025-06-12  17

    (1)什么是IOC 控制反转-(Inversion of Control,缩写为loC) 把原来new对象的这种方式转换成了,sprilg通过反射创建对象的方式spring创建完的对象放到一个容器中,谁需要就给谁注入进去-(获取对象并赋值给引用) 简单说:把创建对象和管理对象的权利交给spring

    思维导图:

    原理分析:

    其实IOC容器,就是一个Map集合,根据你在配置文件中配置的id,找到与之对应的class类,然后利用反射,new出该类的对象!!

    就是在new一个对象的时候不需要自己亲自new,而是用配置文件,利用反射获取。

    ##测试代码:

    pom.xml

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.6.RELEASE</version> </dependency>

    com.lbl.domain.personTest

    package com.lbl.domain; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class personTest { @Test public void test01(){ ClassPathXmlApplicationContext onctext=new ClassPathXmlApplicationContext("applicationContext.xml"); Object person = onctext.getBean("person"); System.out.println(person); } }

    com.lbl.domain.Person

    package com.lbl.domain; public class Person { private int id; private String name; private int age; public Person() { } public Person(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }

    applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="person" class="com.lbl.domain.Person"></bean> </beans>

    运行结果:

    person被new出来了,那为什么都没有值呢,那是因为我这里只是new出来了,并没有赋值,那怎么赋值呢?请看我后面的博客

    Processed: 1.184, SQL: 8