先想一下,正常我们想要创建一个web服务,首先需要下载tomcat,创建web工程,配置各种web.xml,引入spring的配置,各种配置文件一顿倒腾.....下载有了spring boot,你创建一个web工程只需要一个java类,甚至都不需要下载tomcat,直接右键执行就能启动一个web服务。听起来就让人感觉兴奋!

最近我也是工作有需要,需要新建一个微服务的模块。正好公司比较开放,支持搞搞新技术,于是就在同事的怂恿下采用Spring Boot创建了一个工程。使用后发现如果熟练掌握一些配置的技巧,那么其实是事半功倍的。(当然你需要花点时间熟悉一下Spring Boot的流程)。不过创建这样一个工程真的是很简单,下面就先看看效果:

创建Hello world工程

安装jdk和maven

前提条件肯定是要安装jdk和maven,配置好环境变量,这个就不多说了:

xinghailong@DESKTOP-JB5HET6 MINGW64 ~/Documents/workspace/my
$ java -version
java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode) xinghailong@DESKTOP-JB5HET6 MINGW64 ~/Documents/workspace/my
$ mvn -version
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-11T00:41:47+08:00)
Maven home: C:\Users\xinghailong\Documents\soft\apache-maven-3.3.9
Java version: 1.8.0_66, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_66\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos"

然后配置maven依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>xingoo</groupId>
<artifactId>SimpleSpringBoot</artifactId>
<version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <!-- 自动依赖父pom,可以省略很多的配置-->
<!-- 如果已经有了父依赖,那么可以参考:http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#using-boot-maven-without-a-parent -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies> <build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

最后创建一个java类

package main.java.xingoo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; /**
* Created by xinghailong on 2017/7/21.
*/
/*@Configuration
@EnableAutoConfiguration
@ComponentScan*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

并且创建一个Controller(你也可以直接在上面的类中创建请求Mapping)

package main.java.xingoo.web;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; /**
* Created by xinghailong on 2017/7/21.
*/
@RestController
public class TestController {
@RequestMapping("/hello")
public String hello(){
return "hello world!";
}
}

在Application类上直接执行

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.4.RELEASE) 2017-07-21 23:46:50.580 INFO 22236 --- [ main] main.java.xingoo.Application : Starting Application on DESKTOP-JB5HET6 with PID 22236 (C:\Users\xinghailong\Documents\workspace\my\SimpleSpringBoot\target\classes started by xinghailong in C:\Users\xinghailong\Documents\workspace\tiangou\code\workbench)
2017-07-21 23:46:50.588 INFO 22236 --- [ main] main.java.xingoo.Application : No active profile set, falling back to default profiles: default
2017-07-21 23:46:50.700 INFO 22236 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4da4253: startup date [Fri Jul 21 23:46:50 CST 2017]; root of context hierarchy
2017-07-21 23:46:54.086 INFO 22236 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-07-21 23:46:54.117 INFO 22236 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-07-21 23:46:54.118 INFO 22236 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15
2017-07-21 23:46:54.346 INFO 22236 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-07-21 23:46:54.346 INFO 22236 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3653 ms
2017-07-21 23:46:54.684 INFO 22236 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-07-21 23:46:54.713 INFO 22236 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-07-21 23:46:54.715 INFO 22236 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-07-21 23:46:54.717 INFO 22236 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-07-21 23:46:54.717 INFO 22236 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-07-21 23:46:55.302 INFO 22236 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4da4253: startup date [Fri Jul 21 23:46:50 CST 2017]; root of context hierarchy
2017-07-21 23:46:55.472 INFO 22236 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.lang.String main.java.xingoo.web.TestController.hello()
2017-07-21 23:46:55.480 INFO 22236 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-07-21 23:46:55.481 INFO 22236 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-07-21 23:46:55.564 INFO 22236 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-21 23:46:55.564 INFO 22236 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-21 23:46:55.632 INFO 22236 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-21 23:46:56.004 INFO 22236 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-07-21 23:46:56.134 INFO 22236 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-07-21 23:46:56.142 INFO 22236 --- [ main] main.java.xingoo.Application : Started Application in 6.834 seconds (JVM running for 8.969)

在页面访问localhost:8080/hello

就能看到输出信息了。

hello world!

很简单吧!

代码我已经上传到github上面,如果有兴趣的可以直接clone下来使用:https://github.com/xinghalo/SimpleSpringBoot.git

跟着官方文档学习下基本知识

关于注解@EnableAutoConfiguration

其他的内容就不说了,跟之前部署到tomcat差不多,不同的是多了这个注解,这个注解的作用是会去根据配置的pom依赖,自动加载一些类,比如数据库的dataSource等。

关于部署

SpringBoot的项目可以直接打成一个 可执行的jar包,即fat jar。一般情况下java是不支持内嵌jar的,它会在你打包的时候把class抽离出来放在一个jar里面,如果有两个class名称和目录都相同,那么就会出现冲突。因此Spring Boot提供了自己的打包插件,这就需要在build当中引入该plugin:

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

然后,在pom.xml同层目录下,执行命令mvn clean package就可以打包了。

推荐的包层次

com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java

Configuration

在Spring Boot中,一般很少使用xml进行配置,都是基于Class来配置的。如果有一些配置项,那么可以把这个类加上注解@Configuration。如果额外需要引入xml,也可以使用注解@ImportResource添加xml文件

禁用某些配置

比如你的项目根本不需要引入数据库连接池,那么就可以使用exclude进行排除:

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}

使用@SpringBootApplication

这个注解可以当做是@Configuration, @EnableAutoConfiguration and @ComponentScan的合体

使用maven启动

执行下面的命令,也可以通过maven启动spring boot

mvn spring-boot:run

Spring Boot快速搭建Web工程的更多相关文章

  1. 寻找写代码感觉(一)之使用 Spring Boot 快速搭建项目

    写在前面 现在已经是八月份了,我已经荒废了半年居多,不得不说谈恋爱确实是个麻烦的事,谈好了皆大欢喜,分手了就是萎靡不振,需要很长一段时间才能缓过来. 人还是要有梦想的,至于实现只不过是一个契机,但凡不 ...

  2. Spring Boot快速开发Web项目

    我们以前使用Spring框架的时候,需要首先在pom文件中增加对相关的的依赖,然后新建Spring相关的xml文件,而且往往那些xml文件还不会少.然后继续使用tomcat或者jetty作为容器来运行 ...

  3. spring boot 快速生成demo工程 官网生成

    最近一直在弄springboot的项目,居然最近才知道快速生成springBoot工程,原来可以这么简单, 而且官网还提供了生成java或是web项目,需要jpa,模板等服务,直接一键集成.话不多说, ...

  4. Spring Boot 快速搭建的三种方式

    方式一:http://start.spring.io/ 打开浏览器,在地址栏中输入http://start.spring.io/ 如下图:  点击generate project 然后就会有一个zip ...

  5. Spring Boot快速搭建Spring框架

    Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development a ...

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

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

  7. spring boot入门教程——Spring Boot快速入门指南

    Spring Boot已成为当今最流行的微服务开发框架,本文是如何使用Spring Boot快速开始Web微服务开发的指南,我们将使创建一个可运行的包含内嵌Web容器(默认使用的是Tomcat)的可运 ...

  8. Spring-Boot快速搭建web项目详细总结

    最近在学习Spring Boot 相关的技术,刚接触就有种相见恨晚的感觉,因为用spring boot进行项目的搭建是在太方便了,我们往往只需要很简单的几步,便可完成一个spring MVC项目的搭建 ...

  9. Spring Boot 快速入门(IDEA)

    从字面理解,Boot是引导的意思,因此SpringBoot帮助开发者快速搭建Spring框架:SpringBoot帮助开发者快速启动一个Web容器:SpringBoot继承了原有Spring框架的优秀 ...

随机推荐

  1. PAT 1048 数字加密(20)(代码+思路)

    1048 数字加密(20)(20 分) 本题要求实现一种数字加密方法.首先固定一个加密用正整数A,对任一正整数B,将其每1位数字与A的对应位置上的数字进行以下运算:对奇数位,对应位的数字相加后对13取 ...

  2. Angular 通过注入 $location 获取与修改当前页面URL

    //1.获取当前完整的url路径 var absurl = $location.absUrl(); //http://172.16.0.88:8100/#/homePage?id=10&a=1 ...

  3. 2018.07.31 POJ1741Tree(点分治)

    传送门 只是来贴一个点分治的板子(年轻时候写的丑别介意). 代码: #include<cstdio> #include<cstring> #include<algorit ...

  4. hdu-1116(欧拉回路+并查集)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1116 思路:将字符串的头元素和尾元素视为图的x,y节点,然后合并x,y. 如果这个图不连通,则门不能打 ...

  5. gj11 多线程、多进程和线程池编程

    11.1 python中的GIL # coding=utf-8 # gil global interpreter lock (cpython) # python中一个线程对应于c语言中的一个线程 # ...

  6. DatePickerDialog TimePickerDialog

    MainActivity.java        public class MainActivity extends Activity   {       @Override       public ...

  7. 状态机中的RAM注意的问题--减少扇出的办法

    可能我不会抓紧时间,所以做事老是很慢.最近在整维特比译码过程深感自己有这样的毛病. 每天会有一点进展,但是却是一天的时间,感觉别人都做起事情来很快.可能这个东西有点难,做 不做得出来都不要紧,但我的想 ...

  8. python编码(六)

    1. 字符编码简介 1.1. ASCII ASCII(American Standard Code for Information Interchange),是一种单字节的编码.计算机世界里一开始只有 ...

  9. 15) maven dependency scope

    Dependency Scope Dependency scope is used to limit the transitivity of a dependency, and also to aff ...

  10. AWS S3 CLI的安装和配置

    以Ubuntu系统为例,说明如何使用CLI调试AWS S3环境: 1. 安装 # sudo pip install awscli 2. 配置AWS CLI 执行命令aws configure, 注意, ...