Spring---环境搭建和第一个Spring程序

本文介绍了如何创建一个Spring Web MVC项目,从新建Maven父工程到引入Spring Web MVC依赖,再到构建实体类Hello和XML配置文件。通过官方文档,学习如何连接XML配置与实体类,并编写测试类进行验证,输出'HelloSpring'。
摘要由CSDN通过智能技术生成

一.环境搭建

新建一个普通Maven项目,删除src文件夹,作为父工程,修改pom.xml
导入依赖:前往https://mvnrepository.com/搜索Spring依赖,选择Spring Web MVC依赖会帮助我们自动导入其他相关依赖
在这里插入图片描述

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>

二.第一个Spring程序

新建一个子工程Module,spring-01-hellospring,如图建立一个实体类Hello和一个XML文件
在这里插入图片描述

package com.bandit.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 + '\'' +
                '}';
    }
}

XML文件格式我们可以去官方文档拷贝:https://docs.spring.io/spring-framework/docs/5.3.10-SNAPSHOT/reference/html
在这里插入图片描述
改写成我们自己的类

<?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.bandit.pojo.Hello">
        <property name="str" value="Hello Spring"/>
    </bean>

</beans>

在这里插入图片描述
在官方文档中是用ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");来连接xml与实体类的
编写测试类

@Test
    public void Test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        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、付费专栏及课程。

余额充值