案例02 基于xml配置的构造方法注入案例

通过构造方法方式来演示Spring容器在应用中是如何实现依赖注入的,实现Student输出学生姓名和年龄。

1. 创建项目

Idea创建Java项目,项目名称为:case02-spring-student01。

2. 导入spring相关jar包

case02-spring-student01项目下创建lib目录,在lib目录下导入Jar包:

  • 核心包

spring-core-5.3.25.jar、

spring-beans-5.3.25.jar、

spring-context-5.3.25.jar、

spring-expression-5.3.25.jar

  • 测试包

junit-4.6.jar

  • 依赖包

commons-logging-1.2.jar

3. 创建Spring配置文件

src目录下创建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">
    <!-- 将Student类配置给Spring,让Spring创建其实例 -->
    <bean id="student" class="com.wfit.Student">
        <!-- <constructor-arg>元素表示构造方法的一个参数-->
        <constructor-arg name="name" value="zhangsan"></constructor-arg>
        <constructor-arg name="age" value="20"></constructor-arg>
    </bean>
</beans>

4. 创建Student类

src目录下创建com.wfit包,此包目录下创建Student类。

public class Student {

    private String name;
    private int age;

    public Student(String name,int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

5.创建测试类

src目录下创建com.wfit包,此包目录下创建TestStudent测试类。

public class TestStudent {

    @Test
    public void test(){
        //加载applicationContext.xml配置
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        //通过容器获取Student实例
        Student student = applicationContext.getBean("student", Student.class);
        System.out.println(student);
    }

}

6. 执行结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WFIT~SKY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值