在IDEA中实现第一个Spring程序——HelloSpring

1. 新建Maven工程

1、File -> New -> Project -> Maven
在这里插入图片描述

2、选择Next,在Name栏输入hello-spring(项目名),GroupId栏输入com.ju(一般为公司域名的倒序),点击Finish,项目创建完成。
在这里插入图片描述

2. 导入jar包

1、进入Maven官网,搜索Spring,选择Spring Web MVC ,选择最新版本,复制Maven栏中的配置语句:
在这里插入图片描述

2、打开工程中的pom.xml文件,将复制的语句粘贴到里面:
在这里插入图片描述

3. 编写Hello类

1、删除src文件夹,并创建Module(也可以不删除,直接在src编写代码,Module的好处是可以在一个项目中新建多个Module,在学习过程中方便分类学习):
在这里插入图片描述
2、查看右侧Maven菜单,jar包已导入完成:
在这里插入图片描述

3、在spring-01-hellospring\src\main\java下创建com.ju.hello包,在包中创建Hello类,Hello类具体实现如下:

package com.ju.hello;

public class Hello {
    private String str;

    public Hello() {
        this(null);
    }

    public Hello(String str) {
        this.str = str;
    }

    public String getStr() {
        return str;
    }

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

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

4. 构建基于XML的配置bean

ps:Spring中的bean可以理解为Java中的对象。

在hello-spring\src\main\java\resources下新建hello.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">

	<!--
    id: bean 的唯一标识符,相当于对象名
    class: bean 对象所对应的类的全限定名(包名 + 类名)
    -->
    <bean id="hello" class="com.ju.hello.Hello">
        <!-- 这里选择下面的一种方式即可 -->
        <!-- 通过构造器注入 -->
        <constructor-arg name="str" value="Hello Spring!"/>
        <!-- 通过set()注入 -->
        <property name="str" value="Hello Spring!"/>
    </bean>

</beans>

5. 编写测试类

在hello-spring\src\test\java下新建Test类,Test类的具体实现如下:

import com.ju.hello.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        // The ApplicationContext lets you read bean definitions and access them
        ApplicationContext context = new ClassPathXmlApplicationContext("hello.xml");
        // 从容器中获取bean
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

程序的运行结果如下:
在这里插入图片描述

6. 小结

在Spring中,对象的创建不再通过在程序中new一个对象实现,它将所有相关的对象都交给Spring管理,在程序的实现中,我们直接从Spring中拿到所需要的对象。当我们需要修改对象的配置时(如Hello类中的str字段),直接修改配置文件(hello.xml)即可,无需像以前一样修改代码的具体实现。

这种设计模式被称作控制反转(IOC),可以有效的降低代码之间的耦合,在这里IOC的实现方式为依赖注入(DI)。

除了使用XML,Spring还可以通过Java代码(配置类)来装配bean,甚至还可以实现自动装配。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值