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日誌信息 ...