简介
在您第1次接触和学习spring框架的时候,是否因为其繁杂的配置而退却了?在你第n次使用spring框架的时候,是否觉得一堆反复黏贴的配置有一些厌烦?那么您就不妨来试试使用spring boot来让你更易上手,更简单快捷地构建spring应用!
spring boot让我们的spring应用变的更轻量化。比如:你可以仅仅依靠一个java类来运行一个spring引用。你也可以打包你的应用为jar并通过使用java -jar来运行你的spring web应用。
spring boot的主要优点:
快速入门
本章主要目标完成spring boot基础项目的构建,并且实现一个简单的http请求处理,通过这个例子对spring boot有一个初步的了解,并体验其结构简单、开发快速的特性。
系统要求:
本文采用java 1.8.0_73、spring boot 1.3.2调试通过。
使用maven构建项目
1、通过spring initializr工具产生基础项目
访问:
选择构建工具maven project、spring boot版本1.3.2以及一些工程基本信息,可参考下图所示spring initializr
点击generate project下载项目压缩包
2、解压项目包,并用ide以maven项目导入,以intellij idea 14为例:
项目结构解析
通过上面步骤完成了基础项目的创建,如上图所示,spring boot的基础结构共三个文件(具体路径根据用户生成项目时填写的group所有差异):
生成的chapter1application和chapter1applicationtests类都可以直接运行来启动当前创建的项目,由于目前该项目未配合任何数据访问或web模块,程序会在加载完spring之后结束运行。
引入web模块
当前的pom.xml内容如下,仅引入了两个模块:
<dependencies> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> </dependencies>
引入web模块,需添加spring-boot-starter-web模块:
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency>
编写helloworld服务
@restcontroller public class hellocontroller { @requestmapping("/hello") public string index() { return "hello world"; } }
启动主程序,打开浏览器访问http://localhost:8080/hello,可以看到页面输出hello world
编写单元测试用例
打开的src/test/下的测试入口chapter1applicationtests类。下面编写一个简单的单元测试来模拟http请求,具体如下:
@runwith(springjunit4classrunner.class) @springapplicationconfiguration(classes = mockservletcontext.class) @webappconfiguration public class chapter1applicationtests { private mockmvc mvc; @before public void setup() throws exception { mvc = mockmvcbuilders.standalonesetup(new hellocontroller()).build(); } @test public void gethello() throws exception { mvc.perform(mockmvcrequestbuilders.get("/hello").accept(mediatype.application_json)) .andexpect(status().isok()) .andexpect(content().string(equalto("hello world"))); } }
使用mockservletcontext来构建一个空的webapplicationcontext,这样我们创建的hellocontroller就可以在@before函数中创建并传递到mockmvcbuilders.standalonesetup()函数中。
注意引入下面内容,让status、content、equalto函数可用
import static org.hamcrest.matchers.equalto; import static org.springframework.test.web.servlet.result.mockmvcresultmatchers.content; import static org.springframework.test.web.servlet.result.mockmvcresultmatchers.status;
至此已完成目标,通过maven构建了一个空白spring boot项目,再通过引入web模块实现了一个简单的请求处理。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
Mybatis PersistenceException异常:Error building SqlSession The error may exist in SQL Mapper Configur
MyBatis——动态SQL语句——if标签和where标签复合使用
网友评论