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

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

1. 开发环境

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

2. 创建项目

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

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

  1. $ mkdir ng-spring-boot && cd ng-spring-boot
  2. $ gradle init

ng-spring-boot 目录结构如下:

  1. ng-spring-boot tree
  2. .
  3. ├── build.gradle
  4. ├── gradle
  5.    └── wrapper
  6.    ├── gradle-wrapper.jar
  7.    └── gradle-wrapper.properties
  8. ├── gradlew
  9. ├── gradlew.bat
  10. └── settings.gradle
  11. 2 directories, 6 files

然后修改 build.gradle 文件:

  1. buildscript {
  2. ext {
  3. springBootVersion = '1.2.2.RELEASE'
  4. }
  5. repositories {
  6. mavenCentral()
  7. }
  8. dependencies {
  9. classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
  10. }
  11. }
  12. apply plugin: 'java'
  13. apply plugin: 'eclipse'
  14. apply plugin: 'idea'
  15. apply plugin: 'spring-boot'
  16. jar {
  17. baseName = 'ng-spring-boot'
  18. version = '0.0.1-SNAPSHOT'
  19. }
  20. sourceCompatibility = 1.7
  21. targetCompatibility = 1.7
  22. repositories {
  23. mavenCentral()
  24. maven { url "https://repo.spring.io/libs-release" }
  25. }
  26. dependencies {
  27. compile("org.springframework.boot:spring-boot-starter-data-jpa")
  28. compile("org.springframework.boot:spring-boot-starter-web")
  29. compile("org.springframework.boot:spring-boot-starter-actuator")
  30. runtime("org.hsqldb:hsqldb")
  31. testCompile("org.springframework.boot:spring-boot-starter-test")
  32. }
  33. eclipse {
  34. classpath {
  35. containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
  36. containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7'
  37. }
  38. }
  39. task wrapper(type: Wrapper) {
  40. gradleVersion = '2.3'
  41. }

使用 spring-boot-gradle-plugin 插件可以提供一些创建可执行 jar 和从源码运行项目的任务,它还提供了 ResolutionStrategy 以方便依赖中不用写版本号。

3. 创建一个可执行的类

首先,新建一个符合 Maven 规范的目录结构:

  1. $ mkdir -p src/main/java/com/javachen

创建一个 Sping boot 启动类:

  1. package com.javachen;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  4. import org.springframework.context.annotation.ComponentScan;
  5. import org.springframework.context.annotation.Configuration;
  6. @Configuration
  7. @EnableAutoConfiguration
  8. @ComponentScan
  9. public class Application {
  10. public static void main(String[] args) {
  11. SpringApplication.run(Application.class, args);
  12. }
  13. }

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。

上面三个注解还可以用 @SpringBootApplication 代替:

  1. package com.javachen.examples.springboot;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
  5. public class Application {
  6. public static void main(String[] args) {
  7. SpringApplication.run(Application.class, args);
  8. }
  9. }

你也可以修改该类的 main 方法,获取 ApplicationContext:

  1. package com.javachen;
  2. import java.util.Arrays;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.annotation.ComponentScan;
  7. import org.springframework.context.annotation.Configuration;
  8. @SpringBootApplication
  9. public class Application {
  10. public static void main(String[] args) {
  11. ApplicationContext ctx = SpringApplication.run(Application.class, args);
  12. System.out.println("Let's inspect the beans provided by Spring Boot:");
  13. String[] beanNames = ctx.getBeanDefinitionNames();
  14. Arrays.sort(beanNames);
  15. for (String beanName : beanNames) {
  16. System.out.println(beanName);
  17. }
  18. }
  19. }

4. 创建一个实体类

创建一个实体类 src/main/java/com/javachen/model/Item.java:

  1. package com.javachen.model;
  2. import javax.persistence.*;
  3. @Entity
  4. public class Item {
  5. @Id
  6. @GeneratedValue(strategy=GenerationType.IDENTITY)
  7. private Integer id;
  8. @Column
  9. private boolean checked;
  10. @Column
  11. private String description;
  12. public Integer getId() {
  13. return id;
  14. }
  15. public void setId(Integer id) {
  16. this.id = id;
  17. }
  18. public boolean isChecked() {
  19. return checked;
  20. }
  21. public void setChecked(boolean checked) {
  22. this.checked = checked;
  23. }
  24. public String getDescription() {
  25. return description;
  26. }
  27. public void setDescription(String description) {
  28. this.description = description;
  29. }
  30. }

5. 创建控制类

创建一个 Restfull 的控制类,该类主要提供增删改查的方法:

  1. package com.javachen.controller;
  2. import com.javachen.model.Item;
  3. import com.javachen.repository.ItemRepository;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.dao.EmptyResultDataAccessException;
  6. import org.springframework.http.HttpStatus;
  7. import org.springframework.web.bind.annotation.*;
  8. import javax.persistence.EntityNotFoundException;
  9. import java.util.List;
  10. @RestController
  11. @RequestMapping("/items")
  12. public class ItemController {
  13. @Autowired
  14. private ItemRepository repo;
  15. @RequestMapping(method = RequestMethod.GET)
  16. public List<Item> findItems() {
  17. return repo.findAll();
  18. }
  19. @RequestMapping(method = RequestMethod.POST)
  20. public Item addItem(@RequestBody Item item) {
  21. item.setId(null);
  22. return repo.saveAndFlush(item);
  23. }
  24. @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
  25. public Item updateItem(@RequestBody Item updatedItem, @PathVariable Integer id) {
  26. Item item = repo.getOne(id);
  27. item.setChecked(updatedItem.isChecked());
  28. item.setDescription(updatedItem.getDescription());
  29. return repo.saveAndFlush(item);
  30. }
  31. @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
  32. @ResponseStatus(value = HttpStatus.NO_CONTENT)
  33. public void deleteItem(@PathVariable Integer id) {
  34. repo.delete(id);
  35. }
  36. @ResponseStatus(HttpStatus.BAD_REQUEST)
  37. @ExceptionHandler(value = { EmptyResultDataAccessException.class, EntityNotFoundException.class })
  38. public void handleNotFound() { }
  39. }

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

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

6. 创建 JPA 仓库

使用 JAP 来持久化数据:

  1. package com.javachen.repository;
  2. import com.javachen.model.Item;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.Query;
  5. import java.util.List;
  6. public interface ItemRepository extends JpaRepository<Item, Integer> {
  7. @Query("SELECT i FROM Item i WHERE i.checked=true")
  8. List<Item> findChecked();
  9. }

Spring Boot 可以自动配置嵌入式的数据库,包括 H2、HSQL 和 Derby,你不需要配置数据库链接的 url,只需要添加相关的依赖即可。另外,你还需要依赖 spring-jdbc,在本例中,我们是引入了对 spring-boot-starter-data-jpa 的依赖。如果你想使用其他类型的数据库,则需要配置 spring.datasource.* 属性,一个示例是在 application.properties 中配置如下属性:

  1. spring.datasource.url=jdbc:mysql://localhost/test
  2. spring.datasource.username=dbuser
  3. spring.datasource.password=dbpass
  4. spring.datasource.driver-class-name=com.mysql.jdbc.Driver

创建 src/main/resources/application.properties 文件,修改 JPA 相关配置,如:

  1. spring.jpa.hibernate.ddl-auto=create-drop

注意:

SpringApplication 会在以下路径查找 application.properties 并加载该文件:

  • /config 目录下
  • 当前目录
  • classpath 中 /config 包下
  • classpath 根路径下

7. 运行项目

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

  1. $ export JAVA_OPTS=-Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom
  2. $ ./gradlew bootRun

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

  1. $ ./gradlew build && java -jar build/libs/ng-spring-boot-0.0.1-SNAPSHOT.jar

启动过程中你会看到如下内容,这部分内容是在 Application 类中打印出来的:

  1. Let's inspect the beans provided by Spring Boot:
  2. application
  3. beanNameHandlerMapping
  4. defaultServletHandlerMapping
  5. dispatcherServlet
  6. embeddedServletContainerCustomizerBeanPostProcessor
  7. handlerExceptionResolver
  8. helloController
  9. httpRequestHandlerAdapter
  10. messageSource
  11. mvcContentNegotiationManager
  12. mvcConversionService
  13. mvcValidator
  14. org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration
  15. org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
  16. org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
  17. org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$DispatcherServletConfiguration
  18. org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
  19. org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
  20. org.springframework.boot.context.embedded.properties.ServerProperties
  21. org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
  22. org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
  23. org.springframework.context.annotation.internalAutowiredAnnotationProcessor
  24. org.springframework.context.annotation.internalCommonAnnotationProcessor
  25. org.springframework.context.annotation.internalConfigurationAnnotationProcessor
  26. org.springframework.context.annotation.internalRequiredAnnotationProcessor
  27. org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
  28. propertySourcesBinder
  29. propertySourcesPlaceholderConfigurer
  30. requestMappingHandlerAdapter
  31. requestMappingHandlerMapping
  32. resourceHandlerMapping
  33. simpleControllerHandlerAdapter
  34. tomcatEmbeddedServletContainerFactory
  35. viewControllerHandlerMapping

你也可以启动远程调试:

  1. $ ./gradlew build
  2. $ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
  3. -jar build/libs/spring-boot-examples-0.0.1-SNAPSHOT.jar

接下来,打开浏览器访问 http://localhost:8080/items,你会看到页面输出一个空的数组。然后,你可以使用浏览器的 Restfull 插件来添加、删除、修改数据。

8. 添加前端库文件

这里主要使用 Bower 来管理前端依赖,包括 angular 和 bootstrap。

配置 Bower ,需要在项目根目录下创建 .bowerrc 和 bower.json 两个文件。

.bowerrc 文件制定下载的依赖存放路径:

  1. {
  2. "directory": "src/main/resources/static/bower_components",
  3. "json": "bower.json"
  4. }

bower.json 文件定义依赖关系:

  1. {
  2. "name": "ng-spring-boot",
  3. "dependencies": {
  4. "angular": "~1.3.0",
  5. "angular-resource": "~1.3.0",
  6. "bootstrap-css-only": "~3.2.0"
  7. }
  8. }

如果你没有安装 Bower,则运行下面命令进行安装:

  1. npm install -g bower

安装之后下载依赖:

  1. bower install

运行成功之后,查看 src/main/resources/static/bower_components 目录结构:

  1. src/main/resources/static/bower_components
  2. ├── angular
  3. ├── angular-resource
  4. └── bootstrap-css-only

9. 创建前端页面

注意:

前端页面和 js 存放到 src/main/resources/static/ 目录下,是因为 Spring Boot 会自动在 /static 或者 /public 或者 /resources 或者 /META-INF/resources 加载静态页面。

创建 index.html

创建 src/main/resources/static 目录存放静态页面 index.html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <link rel="stylesheet" href="./bower_components/bootstrap-css-only/css/bootstrap.min.css" />
  5. </head>
  6. <body ng-app="myApp">
  7. <div class="container" ng-controller="AppController">
  8. <div class="page-header">
  9. <h1>A checklist</h1>
  10. </div>
  11. <div class="alert alert-info" role="alert" ng-hide="items &amp;&amp; items.length > 0">
  12. There are no items yet.
  13. </div>
  14. <form class="form-horizontal" role="form" ng-submit="addItem(newItem)">
  15. <div class="form-group" ng-repeat="item in items">
  16. <div class="checkbox col-xs-9">
  17. <label>
  18. <input type="checkbox" ng-model="item.checked" ng-change="updateItem(item)"/>
  19. </label>
  20. </div>
  21. <div class="col-xs-3">
  22. <button class="pull-right btn btn-danger" type="button" title="Delete"
  23. ng-click="deleteItem(item)">
  24. <span class="glyphicon glyphicon-trash"></span>
  25. </button>
  26. </div>
  27. </div>
  28. <hr />
  29. <div class="input-group">
  30. <input type="text" class="form-control" ng-model="newItem" placeholder="Enter the description..." />
  31. <span class="input-group-btn">
  32. <button class="btn btn-default" type="submit" ng-disabled="!newItem" title="Add">
  33. <span class="glyphicon glyphicon-plus"></span>
  34. </button>
  35. </span>
  36. </div>
  37. </form>
  38. </div>
  39. <script type="text/javascript" src="./bower_components/angular/angular.min.js"></script>
  40. <script type="text/javascript" src="./bower_components/angular-resource/angular-resource.min.js"></script>
  41. <script type="text/javascript" src="./bower_components/lodash/dist/lodash.min.js"></script>
  42. <script type="text/javascript" src="./app/app.js"></script>
  43. <script type="text/javascript" src="./app/controllers.js"></script>
  44. <script type="text/javascript" src="./app/services.js"></script>
  45. </body>
  46. </html>

初始化 AngularJS

这里使用闭包的方式来初始化 AngularJS,代码见 src/main/resources/static/app/app.js :

  1. (function(angular) {
  2. angular.module("myApp.controllers", []);
  3. angular.module("myApp.services", []);
  4. angular.module("myApp", ["ngResource", "myApp.controllers", "myApp.services"]);
  5. }(angular));

创建 resource factory

代码见 src/main/resources/static/app/services.js :

  1. (function(angular) {
  2. var ItemFactory = function($resource) {
  3. return $resource('/items/:id', {
  4. id: '@id'
  5. }, {
  6. update: {
  7. method: "PUT"
  8. },
  9. remove: {
  10. method: "DELETE"
  11. }
  12. });
  13. };
  14. ItemFactory.$inject = ['$resource'];
  15. angular.module("myApp.services").factory("Item", ItemFactory);
  16. }(angular));

创建控制器

代码见 src/main/resources/static/app/controllers.js :

  1. (function(angular) {
  2. var AppController = function($scope, Item) {
  3. Item.query(function(response) {
  4. $scope.items = response ? response : [];
  5. });
  6. $scope.addItem = function(description) {
  7. new Item({
  8. description: description,
  9. checked: false
  10. }).$save(function(item) {
  11. $scope.items.push(item);
  12. });
  13. $scope.newItem = "";
  14. };
  15. $scope.updateItem = function(item) {
  16. item.$update();
  17. };
  18. $scope.deleteItem = function(item) {
  19. item.$remove(function() {
  20. $scope.items.splice($scope.items.indexOf(item), 1);
  21. });
  22. };
  23. };
  24. AppController.$inject = ['$scope', 'Item'];
  25. angular.module("myApp.controllers").controller("AppController", AppController);
  26. }(angular));

10. 测试前端页面

再一次打开浏览器,访问 http://localhost:8080/ 进行测试。

11. 总结

本文主要是记录快速使用 Spring Boot 和 Gradle 创建 AngularJS 项目的过程。,希望能对你有所帮助。

文中相关的源码在 ng-spring-boot,你可以下载该项目,然后编译、运行代码。

该项目也可以使用 maven 编译、运行:

  1. $ mvn clean package
  2. $ java -jar target/ng-spring-boot-0.0.1-SNAPSHOT.jar

或者直接运行:

  1. $ mvn spring-boot:run

11. 参考文章

原创文章,转载请注明: 转载自JavaChen Blog,作者:Junez
本文链接地址:http://blog.javachen.com/2015/01/06/build-app-with-spring-boot-and-gradle.html
本文基于署名2.5中国大陆许可协议发布,欢迎转载、演绎或用于商业目的,但是必须保留本文署名和文章链接。
如您有任何疑问或者授权方面的协商,请邮件联系我。

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

  1. [转] 使用Spring Boot和Gradle创建项目

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

  2. Spring Boot入门-快速搭建web项目

    Spring Boot 概述: Spring Boot makes it easy to create stand-alone, production-grade Spring based Appli ...

  3. eclipse gradle创建java项目

    参考: https://blog.csdn.net/weixin_33733810/article/details/92438913 一 : 需要在 https://gradle.org/releas ...

  4. SpringBoot25 gradle安装、利用gradle创建SrpingBoot项目

    1 gradle安装 技巧01:gradle依赖JDK或者JRE,而且版本至少时1.7 1.1 下载安装包 到gradle官网下载安装包[PS: 也可以利用命令的方式安装,本案例是利用安装包的方式] ...

  5. 喜大普奔,两个开源的 Spring Boot + Vue 前后端分离项目可以在线体验了

    折腾了一周的域名备案昨天终于搞定了. 松哥第一时间想到赶紧把微人事和 V 部落部署上去,我知道很多小伙伴已经等不及了. 1. 也曾经上过线 其实这两个项目当时刚做好的时候,我就把它们部署到服务器上了, ...

  6. 两个开源的 Spring Boot + Vue 前后端分离项目

    折腾了一周的域名备案昨天终于搞定了. 松哥第一时间想到赶紧把微人事和 V 部落部署上去,我知道很多小伙伴已经等不及了. 1. 也曾经上过线 其实这两个项目当时刚做好的时候,我就把它们部署到服务器上了, ...

  7. Spring Boot框架开发的Java项目在CentOS7上的部署

    需求:上级拿来一份Spring Boot框架开发的Java项目代码让我在服务器上运行起来,只说了一句该框架是自带了Tomcat(不用重新安装Tomcat),一份代码下有两个项目(一个管理端项目,一个用 ...

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

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

  9. 使用spring boot,gradle,idea,js,html创建一个小的前后端程序

    1:配置build.gradle,添加依赖等 buildscript { repositories { mavenCentral() } dependencies { classpath('org.s ...

随机推荐

  1. PagedList.MVC 应用

    1. NuGet 下载 PagedList.MVC 2. View Page @model PagedList.IPagedList<Libaray.Models.Entities.BookMo ...

  2. hidden symbol ... is referenced by DSO

    在Linux上编译Qt的时候configure出来的Makefile传递给g++的参数visiblility=hidden,然后就会调用Qt库所使用的第三方库libpng库源代码函数声明添加上__at ...

  3. 处理emacs-org模式TODO的一个脚本

    处理前: 处理后: Table of Contents 1 前言 2 中文的处理 2.1 vim相关 2.2 perl 相关 3 时间相关 4 程序解析 1 前言 最近风帆问我一个问题,也就是处理or ...

  4. Python Open Flash Chart (pyOFC2) — Home

    Python Open Flash Chart (pyOFC2) - Home pyOFC2 Python Open Flash Chart 2

  5. Linux权限管理(笔记)

    权限管理:r: w:x: 三类用户:u: 属主g: 属组o: 其它用户 chown: 改变文件属主(只有管理员可以使用此命令)# chown USERNAME file,...    -R: 修改目录 ...

  6. Linux 块设备驱动 (一)

    1.块设备的I/O操作特点 字符设备与块设备的区别: 块设备只能以块为单位接受输入和返回输出,而字符设备则以字符为单位. 块设备对于I/O请求有对应的缓冲区,因此它们可以选择以什么顺序进行响应,字符设 ...

  7. thinkphp 一些常用写法

    多表查询:

  8. NTP配置实践

    前言 NTP(Network Time Protocol,网络时间协议)是用来使网络中的各个计算机时间同步的一种协议.不管是平时使用的私人计算机还是在工作中搭建的服务器集群.时间的统一性和准确性是十分 ...

  9. Leetcode 238 Product of Array Except Self 时间O(n)和空间O(1)解法

    1. 问题描写叙述 给定一个n个整数的数组(n>1n>1)nums,返回一个数组output,当中的元素outputioutput_i的值为原数组nums中除numsinums_i之外的全 ...

  10. js转换ascii编码如中文友转换为编码友;可防止乱码