Spring系列 【3、HelloSpring】

这篇博客介绍了如何创建第一个Spring程序——HelloSpring。首先,定义了一个名为Hello的实体类,包含一个字符串属性str及对应的getter和setter方法。接着,配置了Spring的beans.xml文件,声明了一个bean并设置了str属性的值。在测试部分,通过ApplicationContext获取bean并打印其内容,展示Spring如何管理对象。最后,程序运行输出了Hello对象的toString结果。

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

3、HelloSpring

下面我们来编写第一个Spring程序:HelloSpring

3.1、编写实体类

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }
	//set是重点
    public void setStr(String str) {
        this.str = str;
    }

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

3.2、beans配置文件

<?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">
    <!--  使用spring来创建对象,在spring这些都成为bean
    类型 变量名 = new 类型();
    Hello hello = new Hello();

    id = 变量名;
    class = new 的对象
    property 相当于给对象中的属性设置一个值
    -->
    <bean id="hello" class="com.only.dao.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>

3.3、测试

public static void main(String[] args) {
    //获取spring上下文对象
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    //我们的对象现在都在spring中管理了,我们要使用就直接去里面取出来用即可
    Hello hello = (Hello) context.getBean("hello");
    System.out.println(hello.toString());
}

3.4、结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值