Spring入门-----HelloWorld

一、前期准备

1.下载与 Eclipse 版本对应的 STS(spring-tool-suite插件) 并安装
2.准备好以下的jar文件:
这里写图片描述

二、项目具体步骤

1.创建一个名为 spring-1 的 Java Project,导入上述jar包并且BuildPath
2.创建 HelloWorld.java,代码如下:

package com.zxh.spring.beans;

public class HelloWorld {

    private String name;

    public void setName(String name) {
        System.out.println("setName: " + name);
        this.name = name;
    }

    public void hello() {
        System.out.println("hello: " + name);
    }

    public HelloWorld() {
        System.out.println("HelloWorld's Constructor.....");
    }


}

3.在 src 上右键创建 Spring 的配置文件Spring Bean Configuration File,命名为 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 -->
    <!-- id第一个字母小写 利用反射技术,因此class要写全名 -->
    <!-- property中的name属性与Class中的set方法必须相对应,例:setZxh()对应name为zxh -->
    <bean id="helloWorld" class="com.zxh.spring.beans.HelloWorld">
        <property name="name" value="Spring123456"></property>
    </bean>

</beans>

4.创建Main.java,代码如下:

package com.zxh.spring.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {

        /*
        HelloWorld helloWorld  = new HelloWorld();
        helloWorld.setName("zxh");
        */

        //1.  创建 Spring 的 IOC 容器对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        //2.  从 IOC 容器中获取 Bean 的实例对象
        HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");

        //3.  调用hello()方法
        helloWorld.hello();

    }

}

三、运行结果

这里写图片描述

四、结果分析及总结

1.如图所示,Spring会自动帮我们创建Bean实例对象,在 Spring IOC 容器读取 Bean 配置创建 Bean 实例之前, 必须对它进行实例化. 只有在容器实例化后, 才可以从 IOC 容器里获取 Bean 实例并使用.
2.创建好Bean实例对象后还会自动调用 Bean的set方法来设置属性
3.通过 ApplicationContext 的方式创建Spring的IOC容器对象,ApplicationContext 面向使用 Spring 框架的开发者,几乎所有的应用场合都直接使用 ApplicationContext 而非底层的 BeanFactory

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值