Spring学习笔记——第二部分 Spring入门程序

1. 编写实体类Hello.java

package com.zhang.pojo;

public class Hello {
    private String str;

    public void setStr(String str) {
        this.str = str;
    }

    public String getStr() {
        return str;
    }

    @Override
    public String toString(){
        return "Hello{" +
                "str='" + str +"\'" +
                "}";
    }
}

2. 编写配置文件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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="hello" class="com.zhang.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>

</beans>
  • 文件中,第七到第九行代码表示:在Spring容器中创建一个id为hello的bean实例,其中class属性用于指示需要实例化的类,即我们第一步写的Hello类。
  • 同时使用property标签,对Hello类中的str属性进行赋值,值(value)为Spring。
  • 在Spring中,我们一般都将配置文件命名为applicationContext.xml,或者beans.xml

3. 编写测试类

  1. 初始化Spring容器,加载配置文件
  2. 通过容器获取Hello实例
  3. 输出
public static void main(String[] args) {
    //获取Spring的上下文对象
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //我们的对象都在Spring中管理,需要时取出即可
    Hello hello = (Hello) context.getBean("hello");
    System.out.println(hello);
}

4. 测试结果

在这里插入图片描述

  • 观察上图,我们发现,控制台已经正确输出结果,而我们并没有通过new关键字来创建Hello的实例化对象,而是通过Spring容器来获取的实现类对象,这就是Spring IoC容器的工作机制。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值