设为首页 加入收藏

TOP

初识Spring Boot
2014-11-23 19:04:11 】 浏览:5856
Tags:初识 Spring Boot

随着Micro Service的概念越来越多的被提及,Spring Boot在前段时间开始就受到了越来越多人的关注。Spring Boot基于其他的Spring组件,可以帮助开发人员快速的搭建应用系统。这篇博客就简单的记录如何使用Spring Boot搭建一个Hello World网页,以及对比其比起Spring MVC搭建的便捷之处。


项目构建

使用Gradle引入Spring Boot相关依赖:

buildscript {
repositories {
maven { url "http://repo.spring.io/libs-snapshot" }
mavenCentral()
}

dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.0.0.RC1")
}
}

apply plugin: 'java'
apply plugin: 'spring-boot'

ext {
springBootVersion = "1.0.2.RELEASE"
}

dependencies {
repositories {
mavenCentral()
}

compile(
"org.springframework.boot:spring-boot-starter-jetty:$springBootVersion",
"org.springframework.boot:spring-boot-starter-web:$springBootVersion"
)
}

这里,我们使用了spring-boot-starter-jetty,这会帮我们引入embedded jetty的instance,关于embedded jetty,可以移步:《Embedded Server:像写main函数一样写一个server》


定义Controller

@RestController
public class HelloWorldController {
@RequestMapping("/helloworld")
public String helloWorld() {
return "Hello World";
}
}


定义main函数

@ComponentScan
@EnableAutoConfiguration
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}

因为定义了ComponentScan和EnableAutoConfiguration这两个Annotation。所以,当HelloWorldApplication被启动时,会自动的找到并配置HelloWorldController。


启动服务器

你可以在IDE中直接启动服务器,也可以通过先把应用打包成一个jar包,运用命令行启动:gradle build

得到了spring-boot-helloworld.jar

java -jar spring-boot-helloworld.jar

访问http://localhost:8080/helloworld就可以看到应用启动起来了



初识

Spring Boot还有其他一些好东西,但初次接触,还是能够感受到不少好处:

1. 没有web.xml或者SpringMVC中dispatchServlet那样繁琐的配置。以前每启动开发一个新项目,都需要花一些无谓的时间配置这些相同的东西。

2. 更方便的集成Embedded Server。对比前面提到的那篇Jetty Embedded Server的博客,这个还要方便一些

3. 更多更方便的集成。Spring Boot不止只有这篇博客提到的这一点儿东西,还有很多其他的jar包可以用来方便我们开发RESTFul Service以及方便和数据库的交互。



参考资料

Spring Boot Reference

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-first-application-executable-jar

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇字符串匹配KMP学习 下一篇Java 并发专题 : Timer的缺陷 用..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目