Spring是如何通过IOC来创建对象的?一文足矣

本文详细探讨了Spring如何通过IOC创建对象,包括无参构造函数创建、别名配置、Bean定义以及导入XML配置。通过实例展示了Spring如何管理、装配对象,最后提供了关于Spring源码的分析图谱和相关面试知识点。

前言

在这里插入图片描述

一、IOC如何获取对象

面试官:SpringIOC是如何创建对象的?

1.1 Spring是如何获取对象的?

①新建一个maven项目后导入webmvc的依赖:因为webmvc包含了很多其他依赖,为了省事,干脆导入一个总的,方便省事!版本嘛!个人比较喜欢用最新版。

    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.5</version>
    </dependency>
1.2.3.4.5.

②新建实体测试类:

public class Person {
   
   
    private String name;
    private int age;
    private String like;
    private String high;
    //get、set、tostring方法为了篇幅省略,可以自己加或者使用lombok
}
1.2.3.4.5.6.7.

③在resources目录下新建ContextAplication.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="entity.Person">
        <property name="age" value="23"></property>
        <property name="name" value="丁大大"></property>
        <property name="like" value="钓鱼"></property>
        <property name="high" value="173"></property>
    </bean>

</beans>
1.2.3.4.5.6.7.8.9.10.11.12.

④以上前提之后,你会发现你的测试Person类种发生了变化:点击可以跳转到指定的xml位置哦~
在这里插入图片描述
⑤测试:

Context.getBean() 不指定类时,需要强制转换,所以建议使用第二种方式来获取对象

public class Test {
   
   
    public static void main(String[] args) {
   
   
        ApplicationContext Context = new ClassPathXmlApplicationContext("ContextAplication.xml");
//        Person person = (Person) Context.getBean("Person");//这里不指定的话需要强转,建议用下面的方式来拿对象
        Person person = Context.getBean("Person",Person.class);
        System.out.println(person);
    }
}

1.2.3.4.5.6.7.8.

⑥执行结果如下:成功拿到值!
在这里插入图片描述
⑦总结:

控制: 传统的程序对象的创建是由程序来控制创建的。
反转: 交给Spring容器来创建对象,而程序只负责被动的接收对象。这就是反转。
依赖注入: 就是通过set方法来注入的。

1.2 改造案例由xml选择创建对象

①xml:

 <bean id="StudentMapperImpl" class="mapper.impl.StudentMapperImpl"/>
    <bean id="TeacherMapperImpl" class="mapper.impl.TeacherMapperImpl"/>

    <bean id="PersonServiceImpl" class="service.impl.PersonServiceImpl">
        <property name="studentMapper" ref="StudentMapperImpl"/>
    </bean
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值