Hello Spring 第一个Spring程序

37 篇文章 0 订阅
12 篇文章 0 订阅
本文介绍了如何在Spring框架中配置bean并为属性赋值。示例展示了创建一个名为Hello的简单Java类,然后在`applicationContext.xml`配置文件中定义bean,并通过``标签设置`str`属性值为'Spring'。最后,通过测试类从Spring容器中获取并打印该bean的实例。
摘要由CSDN通过智能技术生成
package com.yyf.pojo;

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

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

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

2.配置applicationContext.xml   创建bean  并为str属性赋值 Spring

<?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">
 <!-- 用spring来创建对象,在spring中对象都叫bean 一个bean对应创建一个对象-->
<!--   类  类对象=new 类();-->
<!-- id等于 类对象
     class 等于new 的对象
     property 给类属性赋值-->
<bean id="hello" class="com.yyf.pojo.Hello">
 <property name="str" value="Spring"/>
</bean>
</beans>

3.测试类

import com.yyf.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    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 ());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值