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

原理分析:
其实IOC容器,就是一个Map集合,根据你在配置文件中配置的id,找到与之对应的class类,然后利用反射,new出该类的对象!!
就是在new一个对象的时候不需要自己亲自new,而是用配置文件,利用反射获取。

##测试代码:
pom.xml
<dependency><groupId>org.springframeworkgroupId><artifactId>spring-contextartifactId><version>5.2.6.RELEASEversion>
dependency>
com.lbl.domain.personTest
package com.lbl.domain;import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class personTest {@Testpublic void test01(){ClassPathXmlApplicationContext onctext=newClassPathXmlApplicationContext("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;}@Overridepublic String toString() {return "Person{" +"id=" + id +", name='" + name + '\'' +", age=" + age +'}';}
}
applicationContext.xml
<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出来了,并没有赋值,那怎么赋值呢?请看我后面的博客
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
