小白入门spring——IOC

本文介绍了Spring的IOC(控制反转)概念,通过实例展示了如何使用Spring容器通过反射创建并管理对象。测试代码演示了如何通过ClassPathXmlApplicationContext加载配置文件并获取Bean。IOC容器实际上是一个Map,根据配置文件中的id查找并创建对象。虽然对象被成功创建,但尚未赋值。后续内容将探讨如何为对象注入属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • (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出来了,并没有赋值,那怎么赋值呢?请看我后面的博客

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值