初识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

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值