第一讲:spring版HelloWorld实现

1,打开eclipse,新建一个Java项目,取名Spring401
第一讲:spring版HelloWorld实现
第一讲:spring版HelloWorld实现
2,spring的核心包:在项目下新建一个spring文件夹,将核心包(spring的核心包下载地址:https://pan.baidu.com/s/1bF4bXH157iFVdXCoQs-mxA 密码:08t7)copy进去,再Add to Build Path
第一讲:spring版HelloWorld实现
3, 在src下面,新建com.cruise.service 包,包下 Test类;在src下面,新建com.cruise.test 包,包下 HelloWorld类,在HelloWorld下写say()方法,
package com.cruise.test;

public class HelloWorld {

    public void say(){
       System.out.println("HelloWorld!");
    }
}
4,在src下粘贴beans.xml文件(beans.xml文件下载地址:https://pan.baidu.com/s/1bF4bXH157iFVdXCoQs-mxA 密码:08t7),在 beans.xml中,用spring的方式new一个对象,
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="helloworld" class="com.cruise.test.HelloWorld">
  
beans>

  • 5,在test类下,写main()方法, 在main()方法中,首先加载beans.xml,然后根据beans.xml中定义的id来获取对象(注意需要强转),在用这个对象调say()方法。
  • package com.cruise.service;

    import org.springframework.context.support.ClassPathXmlApplicationContext;

    import com.cruise.test.HelloWorld;

    public class Test {

        public static void main(String[] args) {
           ClassPathXmlApplicationContext CA = new ClassPathXmlApplicationContext("beans.xml");
           HelloWorld helloWorld = (HelloWorld)CA.getBean("helloworld");
  •        //helloworld 为beans.xml中定义的id
           helloWorld.say();
        }
    }
    6,执行main方法,测试