先想一下,正常我们想要创建一个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. Devexpress ChartControl 柱状图简单例子

    //using DevExpress.XtraEditors; //using DevExpress.XtraCharts; // Create an empty chart. ChartContro ...

  2. jQuery 操作 html5 data-* 属性

    Html 部分: <a class="nav-item" href="javascript: void(0)" data-id="{{$item ...

  3. Devexpress VCL Build v2013 vol 13.2.5 发布

    支持xe6 了,但是承诺的功能在哪里? What's New in 13.2.5 (VCL Product Line)   New Major Features in 13.2 What's New ...

  4. XE4 for ios 谨慎处理字符串

    由于xe4 for ios  里面的字符串处理有变化,具体可以参考官方文档,这两天帮一个朋友调试ios 的 应用,由于没有注意这一块,折腾了很长时间.特此记录下来,希望其他人不要走弯路. 以下面代码为 ...

  5. [GO]删除切片的某个值

    func removePro(ddbenv []*model.EnvInfo, k int) []*model.EnvInfo { :]...) } for k, v := range ddbenv ...

  6. 怎样使用word2013发布csdn博客

    目前大部分的博客作者在用Word写博客这件事情上都会遇到以下3个痛点: 1.所有博客平台关闭了文档发布接口,用户无法使用Word,Windows Live Writer等工具来发布博客.使用Word写 ...

  7. struts2 action 中autowired 不能注入

    一.pom.xml <dependency> <groupId>org.apache.struts</groupId> <artifactId>stru ...

  8. (网络流 最大流 Dinic || SAP)Control -- hdu --4289

    链接: http://acm.hdu.edu.cn/showproblem.php?pid=4289 http://acm.hust.edu.cn/vjudge/contest/view.action ...

  9. 软件工程作业 - 实现WC功能(java)

    项目地址:https://github.com/yogurt1998/WordCount 要求 基本要求 -c 统计文件字符数(实现) -w 统计文件单词数(实现) -l 统计文件行数(实现) 扩展功 ...

  10. EBS xml publisher中文乱码

    http://www.cnblogs.com/benio/archive/2011/11/22/2259313.html   由于本机环境问题,导致做的xml publisher报表跑不出来. 无法显 ...