001. Spring HelloWorld

1、創建Java項目:File -> New -> Java Project

2、引入必要jar包,項目結構如下
項目結構

3、創建HelloWorld服務類HelloWorld.java

package com.spring.service;

public class HelloWorld {

    public void welcome() {
        System.out.println("Welcome to spring framework!");
    }

}

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 id="helloWorld" class="com.spring.service.HelloWorld"></bean>

</beans>

5、創建Spring測試類SpringUnit.java

package com.spring.junit;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.service.HelloWorld;

public class SpringUnit {

    @Test
    public void test() {

        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
        helloWorld.welcome();

        ctx.close();
    }

}

6、測試結果

... 省略Spring日誌信息 ...

Welcome to spring framework!

... 省略Spring日誌信息 ...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章