Spring的HelloWorld

Spring模块:

 

使用 Eclipse 开发,要先安装 Spring Tool Suite。

安装过程中,只勾选 Spring IDE 结尾(4个)的即可,并把联网进行更新去掉(否则联网速度会变慢)。

 

开发步骤:

1. 加入jar包(5个)

 

 

2. 创建一个 javaBean 类

package cn.jmu.spring.beans;

public class HelloWorld {

    private String name;
    
    public void setName(String name) {
        System.out.println("setName 方法执行...setName: " + name);
        this.name = name;
    }
    
    public void hello(){
        System.out.println("Hello: " + name);
    }
    /*
     * 构造函数,用来查看该类的对象是什么时候创建的
     */
    public HelloWorld(){
        System.out.println("HelloWorld 对象创建...");
    }
}

 

3. 在src下新建一个 Spring Bean Configuration file 文件,一般命名为:applicationContext.xml ,在这个文件中配置 bean。

<?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 -->
    <bean id="helloWorld" class="cn.jmu.spring.beans.HelloWorld"> <!-- 这里其实是使用了反射来创建一个对象。 -->
        <!-- 为 HelloWorld 类的 name 属性赋值,即会执行 HelloWorld 的 setName方法  -->
        <property name="name" value="Sky"></property>
    </bean>

</beans>

 

4. 使用 IOC 容器创建对象和调用对象的方法。

package cn.jmu.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("Sky");
         * helloWorld.hello();
         */
        //1. 创建 Spring 的 IOC 容器对象,ApplicationContext 代表 IOC 容器
        //ClassPathXmlApplicationContext 是 ApplicationContext 接口的实现类,该实现类从类路径下加载xml配置文件。
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2. 从 IOC 容器中获取 Bean 实例
        HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
        //3. 调用类的方法
        helloWorld.hello();
    }

}

 

输出结束:

这就是简单的 Spring HelloWorld。

 

扩展:

为了了解执行过程,先把获取 Bean 对象和调用对象方法注释掉,只保留 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml")。

其输出结果为:

所以,当执行这句代码的时候,Spring 的容器已经帮我们利用反射创建好对象,并根据配置文件把相应的值赋给对象的属性。接下来我们只要获取该对象就可以使用它提供的方法了。

 

posted @ 2016-10-13 19:56  Sky.宾桀锋  阅读(233)  评论(0编辑  收藏  举报