一直想写点关于spring学习系列的东西,一是可以好好的记录下自己的学习历程,二是可以跟大家一起分享spring学习,共同进步。目前spring版本已进入5时代,我们就以最新版本作为学习基础。废话不多说,我们直接进入正题。首先我介绍下我的开发环境,搭建好了开发环境我们就可以开始进入spring的学习。
JDK版本:1.8
IDE工具:Spring Tool Suite 3.9.4.RELEASE (此工具可以从spring官网下载)
关于内容我尽量会以官方的帮助文档作为基线,然后去讲述内容。
我们来开启第一个例子吧。首先准备好相关的spring jar包,我们下载spring的时候,一般也会把所有的jar下载下来,我已经下载下来了,如下(只截取了部分jar):
作为第一个简单的例子我们使用的jar只是其中几个。如下图,把这些JAR加入到类路径下就可以用了。其中junit-4.12.jar是用来写测试用的。在此需要注意下junit-4.12.jar与hamcrest-core-1.3.jar是配合着使用的,也就是说junit-4.12.jar需要依赖后者这个JAR。
接下来我们写一个HelloWorld类,如下图:
package com.springioc.chapter1;
public class HelloWorld {
public void hello() {
System.out.println("Hello World!");
}
}
接着准备好配置文件: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.springioc.chapter1.HelloWorld"/>
</beans>
接着我们写个测试类。
package com.springioc.chapter1;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorldTest {
@Test
public void testHelloWorld() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationcontext.xml");
HelloWorld helloWorld = (HelloWorld)ctx.getBean("helloWorld");
helloWorld.hello();
}
}
运行结果如下:
至此我们基于spring的helloWorld就完成了。希望能对大家有帮助尤其是刚接触spring学习的人。