Spring——第一个Spring程序HelloSpring

Spring——第一个Spring程序HelloSpring

1.创建普通的Maven项目
在这里插入图片描述
2.导入jar包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.9.RELEASE</version>
</dependency>

我们可以看到,只要导入spring-webmvc这个包,Maven就会自动导入依赖的其他jar包
在这里插入图片描述
3.创建pojo

package com.muhan.pojo;

public class User {
    private String name;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

4.编写Spring的配置文件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">

    
    <!--bean就是一个Java对象,由Spring管理和创建-->
    <!--
        相当于:
         User user = new User();
         user.setName="张三";
        id是对象名,class是要托管的对象
    -->
    <bean id="user" class="com.muhan.pojo.User">
        <property name="name" value="张三"/>
    </bean>

    <!--
         相当于:
         User user2 = new User();
         user.setName="李四";
    -->
    <bean id="user2" class="com.muhan.pojo.User">
        <property name="name" value="李四"/>
    </bean>

</beans>

5.测试

import com.muhan.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserTest {
    @Test
    public void test(){
        //获取ClassPathXmlApplicationContext对象,关联spring配置文件applicationContext.xml
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取对象名为user的对象
        User user = (User) context.getBean("user");
        System.out.println(user);

        //获取对象名为user2的对象
        User user2 = (User) context.getBean("user2");
        System.out.println(user2);
    }
}

结果展示:
在这里插入图片描述

6.项目结构
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值