Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

本文主要是记录使用 Spring Boot 和 Gradle 创建项目的过程,其中会包括 Spring Boot 的安装及使用方法,希望通过这篇文章能够快速搭建一个项目。

开发环境

  • 操作系统: mac
  • JDK:1.7.0_60
  • Gradle:2.2.1

创建项目

你可以通过 Spring Initializr 来创建一个空的项目,也可以手动创建,这里我使用的是手动创建 gradle 项目。

参考使用Gradle构建项目 创建一个 helloworld 项目,执行的命令如下:

$ mkdir helloworld && cd helloworld
$ gradle init

helloworld 目录结构如下:

➜  helloworld  tree
.
├── build.gradle
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle 2 directories, 6 files

然后修改build.gradle文件:

buildscript {
repositories {
maven { url "https://repo.spring.io/libs-release" }
mavenLocal()
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.10.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
jar {
baseName = 'helloworld'
version = '0.1.0'
}
repositories {
mavenLocal()
mavenCentral()
maven { url "https://repo.spring.io/libs-release" }
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("junit:junit")
}
task wrapper(type: Wrapper) {
gradleVersion = '2.2.1'
}

创建一个实体类

新建一个符合Maven规范的目录结构, src/main/java/hello:

$ mkdir -p src/main/java/hello

创建一个实体类 src/main/java/hello/Greeting.java:

package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}

创建控制类

创建一个标准的控制类 src/main/java/hello/GreetingController.java:

package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public @ResponseBody Greeting greeting(
@RequestParam(value="name", required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}

Greeting 对象会被转换成 JSON 字符串,这得益于 Spring 的 HTTP 消息转换支持,你不必人工处理。由于 Jackson2 在 classpath 里,Spring的 MappingJackson2HttpMessageConverter 会自动完成这一工作。

上面的代码还可以这样写:

package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", required=false, defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}

这段代码使用 Spring4 新的注解: @RestController ,表明该类的每个方法返回对象而不是视图。它实际就是 @Controller@ResponseBody 混合使用的简写方法。

创建一个可执行的类

尽管你可以将这个服务打包成传统的 WAR 文件部署到应用服务器,但下面将会创建一个独立的应用,使用 main 方法可以将所有东西打包到一个可执行的jar文件。并且,你将使用 Sping 对内嵌 Tomcat servlet 容器的支持,作为 HTPP 运行时环境,没必要部署成一个 tomcat 外部实例。

创建一个包含 main 方法的类 src/main/java/hello/Application.java:

package hello;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}

main 方法使用了 SpringApplication 工具类。这将告诉Spring去读取 Application 的元信息,并在Spring的应用上下文作为一个组件被管理。

@Configuration 注解告诉 spring 该类定义了 application context 的 bean 的一些配置。

@ComponentScan 注解告诉 Spring 遍历带有 @Component 注解的类。这将保证 Spring 能找到并注册 GreetingController,因为它被 @RestController 标记,这也是 @Component 的一种。

@EnableAutoConfiguration 注解会基于你的类加载路径的内容切换合理的默认行为。比如,因为应用要依赖内嵌版本的 tomcat,所以一个tomcat服务器会被启动并代替你进行合理的配置。再比如,因为应用要依赖 Spring 的 MVC 框架,一个 Spring MVC 的 DispatcherServlet 将被配置并注册,并且不再需要 web.xml 文件。

你还可以添加 @EnableWebMvc 注解配置 Spring Mvc。

运行项目

可以在项目根路径直接运行下面命令:

./gradlew bootRun

也可以先 build 生成一个 jar 文件,然后执行该 jar 文件:

./gradlew build && java -jar build/libs/helloworld-0.1.0.jar

启动过程中你回看到如下内容:

Let's inspect the beans provided by Spring Boot:
application
beanNameHandlerMapping
defaultServletHandlerMapping
dispatcherServlet
embeddedServletContainerCustomizerBeanPostProcessor
handlerExceptionResolver
helloController
httpRequestHandlerAdapter
messageSource
mvcContentNegotiationManager
mvcConversionService
mvcValidator
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.context.embedded.properties.ServerProperties
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
propertySourcesBinder
propertySourcesPlaceholderConfigurer
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
simpleControllerHandlerAdapter
tomcatEmbeddedServletContainerFactory
viewControllerHandlerMapping

测试

打开浏览器访问 http://localhost:8080/greeting ,可以看到页面输出下面内容:

{"id":1,"content":"Hello, World!"}

添加一个参数,访问 http://localhost:8080/greeting?name=User ,这时候页面输出下面内容:

{"id":2,"content":"Hello, User!"}

创建静态页面

创建 public/hello.js:

$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/greeting"
}).then(function(data, status, jqxhr) {
$('.greeting-id').append(data.id);
$('.greeting-content').append(data.content);
console.log(jqxhr);
});
});

创建一个页面 public/index.html:

<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="hello.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
<h4>Response headers:</h4>
<div class="response-headers">
</div>
</body>
</html>

现在可以使用 Spring Boot CLI 启动一个嵌入式的 tomcat 服务来访问静态页面,你需要创建 app.groovy 告诉 Spring Boot 你需要运行 tomcat:

@Controller class JsApp { }

Spring Boot CLI 在 mac 系统上通过 brew 安装的方法如下:

brew tap pivotal/tap
brew install springboot

接下来可以指定端口运行一个 tomcat:

spring run app.groovy -- --server.port=9000

总结

本文主要参考 Sping 官方例子来了解和熟悉使用 Gradle 创建 Spring Boot 项目的过程,希望能对你有所帮助。

[转] 使用Spring Boot和Gradle创建项目的更多相关文章

  1. 使用Spring Boot和Gradle创建AngularJS项目

    Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的 ...

  2. Spring Boot构建的Web项目如何在服务端校验表单输入

    本文首发于个人网站:Spring Boot构建的Web项目如何在服务端校验表单输入 这个例子用于演示在Spring Boot应用中如何验证Web 应用的输入,我们将会建立一个简单的Spring MVC ...

  3. spring cloud和spring boot两个完整项目

    spring cloud和spring boot两个完整项目 spring cloud 是基于Spring Cloud的云分布式后台管理系统架构,核心技术采用Eureka.Fegin.Ribbon.Z ...

  4. Spring Boot 2+gRPC 学习系列1:搭建Spring Boot 2+gRPC本地项目

    Spring Boot 2+gRPC 学习系列1:搭建Spring Boot 2+gRPC本地项目 https://blog.csdn.net/alinyua/article/details/8303 ...

  5. 10个Spring Boot快速开发的项目,接私活利器(快速、高效)

    本文为大家精选了 码云 上优秀的 Spring Boot 语言开源项目,涵盖了企业级系统框架.文件文档系统.秒杀系统.微服务化系统.后台管理系统等,希望能够给大家带来一点帮助:) 1.项目名称:分布式 ...

  6. 八个开源的 Spring Boot 前后端分离项目,一定要收藏!

    八个开源的 Spring Boot 前后端分离项目 最近前后端分离已经在慢慢走进各公司的技术栈,不少公司都已经切换到这个技术栈上面了.即使贵司目前没有切换到这个技术栈上面,我们也非常建议大家学习一下前 ...

  7. Spring Boot + JPA 多模块项目无法注入 JpaRepository 接口

    问题描述 Spring Boot + JPA 多模块项目,启动报异常: nested exception is org.springframework.beans.factory.NoSuchBean ...

  8. Github点赞超多的Spring Boot学习教程+实战项目推荐!

    Github点赞接近 100k 的Spring Boot学习教程+实战项目推荐!   很明显的一个现象,除了一些老项目,现在 Java 后端项目基本都是基于 Spring Boot 进行开发,毕竟它这 ...

  9. [转]通过Spring Boot三分钟创建Spring Web项目

    来源:https://www.tianmaying.com/tutorial/project-based-on-spring-boot Spring Boot简介 接下来我们所有的Spring代码实例 ...

随机推荐

  1. Action class [userAction] not found

    今天在做SSI框架整合的时候报了一个这样的错误:Action class [userAction] not found - action - file:F:\workspace\.metadata\. ...

  2. 使用JDBC连接数据库

    JDBC(Java Data Base Connectivity)数据库连接,我们在编写web应用或java应用程序要连接数据库时就要使用JDBC.使用JDBC连接数据库一般步骤有: 1.加载驱动程序 ...

  3. YesFInder - Web File Manager 网页文件管理系统

    开发原由: 原来想找一下实现可视化图片上传程序,先找了ckfinder,发现居然是收费的,而且用起来也不顺手,于是想能不能自己写一个.想到这就立即动手,花2天时间完成初步功能,然后再花了3天完善.目前 ...

  4. javascript 计时器,消失计时器

    var setId= setInterval(function () { alert('点我'); }, 1000); onload = function () { //消灭计时器 clearInte ...

  5. PPT2010中设置音乐播放停止位置

    ppt不仅只是制作幻灯片的效果,而且在制作幻灯片过程中,由于内容很多,每个版块想要呈现的效果是不同的,那么配乐的风格自然也是不同.如何让我们插入的音乐在合适的内容的时候播放和停止呢,下面就来教大家具体 ...

  6. java的类加载机制

    1.概述 Class文件由类装载器装载后,在JVM中将形成一份描述Class结构的元信息对象,通过该元信息对象可以获知Class的结构信息:如构造函数,属性和方法等,Java允许用户借由这个Class ...

  7. 之前C#代码的重新设计

    /* 我用python重构了一把这个代码 大家的反应似乎是过度设计了 好吧,我决定不那么激进,采用更中庸一些的重构 我也有些疑惑: 是否如果重构后的代码比重构前要多,就算过度了呢? */ void m ...

  8. VM虚拟机上 实现CentOS 6.X下部署LVS(DR)+keepalived实现高性能高可用负载均衡

    一.简介 LVS是Linux Virtual Server的简写,意即Linux虚拟服务器,是一个虚拟的服务器集群系统.本项目在1998年5月由章文嵩博士成立,是中国国内最早出现的自由软件项目之一. ...

  9. Java中匿名类的两种实现方式(转)

    使用匿名内部类课使代码更加简洁.紧凑,模块化程度更高.内部类能够访问外部内的一切成员变量和方法,包括私有的,而实现接口或继承类做不到.然而这个不是我说的重点,我说的很简单,就是匿名内部类的两种实现方式 ...

  10. 【Linux】鸟哥的Linux私房菜基础学习篇整理(十二)

    1. depmod [-Ane]:更新内核模块依赖.参数:无参数:depmod会主动分析目前内核的模块,并重新写入/lib/modules/$(uname -r)/modules.dep中:-A:de ...