Spring 框架简述 (二)

本文深入探讨Spring框架中的依赖注入,包括基于XML的配置创建对象、依赖注入的分类、通过set方法注入以及自动注入(byName和byType)。通过实例展示了如何在Spring中使用这些注入方式,以实现更灵活、可扩展的系统架构。
摘要由CSDN通过智能技术生成

Spring 容器创建对象的方式

接上简述一
https://blog.csdn.net/kaema/article/details/121622097
(注:案例中的代码都是沿用简述一的代码,若有兴趣可以点击上面的链接查看)

一已经说过使用默认的构造方法创建对象,接下来就是使用其他方法创建对象

在实体类 Student 中添加带参数的构造方法:

public Student(Integer id, String name, String classRoom) {
   
    this.id = id;
    this.name = name;
    this.classRoom = classRoom;
}

创建工厂类:

package com.imok.pojo;

public class Factory {
   

    /**
     * 实例方法
     */
    public Student instanceFun(){
   
        System.out.println("Factory--------instanceFun");
        return new Student(1,"小白","三班");
    }

    /**
     * 静态方法
     */
    public static Student staticFun(){
   
        System.out.println("Factory---------staticFun");
        return new Student(2,"小黑","四班");
    }

}

由于怕麻烦就放在pojo包下了…

创建新的配置文件 createType.xml:
通过默认构造方法创建

<!--1、通过默认构造方法-->
    <bean id="student1" class="com.imok.pojo.Student"></bean>

通过带参数的构造方法创建

<!--2、通过带参数的构造方法-->
   <bean id="student2" class="com.imok.pojo.Student">
       <!--name:表示参数的名称-->
       <constructor-arg name="id" value="7"/>
       <constructor-arg name="name" value="圣枪哥"/>
       <constructor-arg name=
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值