Spring Boot快速搭建Web工程

先想一下,正常我们想要创建一个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
posted @ 2017-07-22 00:02  xingoo  阅读(9418)  评论(1编辑  收藏  举报