小白入门spring——IOC
发布日期:2021-06-30 18:22:40 浏览次数:3 分类:技术文章

本文共 1780 字,大约阅读时间需要 5 分钟。

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

思维导图:

在这里插入图片描述

原理分析:

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

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

在这里插入图片描述

##测试代码:

pom.xml

org.springframework
spring-context
5.2.6.RELEASE

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

运行结果:

在这里插入图片描述

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

转载地址:https://libolin.blog.csdn.net/article/details/108961007 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:spring简介(思维导图)
下一篇:途牛旅游项目——搜索与分页的后台代码

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月09日 05时41分46秒