Sprint Boot入门(1):创建第一个Spring Boot应用

搭建工程

注:建议使用eclipse的STS插件创建Spring项目,而不是下面的Gradle项目,否则会导致有一些Spring文件不存在。

new Gradle Project,如下

点next,如下选择第一个选项Gradle wrapper

点击next,点finish

工程搭建好后,如下:

配置Gradle

配置build.gradle文件如下:

plugins {
    id 'org.springframework.boot' version '1.5.4.RELEASE'
    id 'java'
    id 'eclipse'
}

jar {
    baseName = 'myproject'
    version =  '0.0.1'
}

jar.into('/') {  
    from('src/main/java')  
}  //稍后,打包时介绍

repositories { jcenter() } dependencies { compile("org.springframework.boot:spring-boot-starter-web") testCompile("org.springframework.boot:spring-boot-starter-test") }

 保存后,右击该工程 -> Gradle -> ReFresh Gradle Project,这样Gradle便会根据配置自动下载依赖包。

编写代码

在目录src/main/java下创建类文件Example.java,并输入代码如下:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {
	@RequestMapping("/")
	String home() {
		return "Hello World!";
	}

	public static void main(String[] args) throws Exception {
		SpringApplication.run(Example.class, args);
	}
}

以下对上面使用的几个注解作简单的解释:

@RestController

为了方便,我们不使用@ResponseBody来注解所有@RequestMapping方法,取而代之使用@RestController。@RestController注解组合了@ResponseBody@Controller,因此可以用@RestController代替这两个注解。

@Controller

dispatcher会扫描被该注解所注解的类,以查找映射的方法并检测@RequestMapping注解

@RequestMapping

使用该注解可以映射URL到一个类或者特定的处理方法上。

@EnableAutoConfiguration

Spring Boot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置你的Spring应用。自从spring-boot-starter-web添加了Tomcat和Spring MVC,auto-configuration默认你开发的是一个web应用,并设置相应的Spring。

main方法:Java应用的入口。main方法通过调用SpringApplication.run方法把权利转交给SpringApplication类。SpringApplication会自动配置Tomcat web服务器。我们需要把Example.class作为参数传递给run方法,告知SpringApplication这是一个Spring的首要组件。

运行Web应用

在这里使用Boot Dashboard启动应用。图标如下:

点击以后出现以下界面:

右击GradleProject_02,点击(Re)start,出现以下启动信息:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2017-06-28 16:11:59.652  INFO 6627 --- [           main] Example                                  : Starting Example on wuchao-Lenovo with PID 6627 (/home/wuchao/eclipse-jee/workspace/GradleProject_02/bin started by wuchao in /home/wuchao/eclipse-jee/workspace/GradleProject_02)
2017-06-28 16:11:59.655  INFO 6627 --- [           main] Example                                  : No active profile set, falling back to default profiles: default
2017-06-28 16:11:59.771  INFO 6627 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@78dd667e: startup date [Wed Jun 28 16:11:59 CST 2017]; root of context hierarchy
2017-06-28 16:12:02.864  INFO 6627 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-06-28 16:12:02.881  INFO 6627 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-06-28 16:12:02.882  INFO 6627 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
2017-06-28 16:12:03.086  INFO 6627 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-06-28 16:12:03.087  INFO 6627 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3324 ms
2017-06-28 16:12:03.236  INFO 6627 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-06-28 16:12:03.240  INFO 6627 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-06-28 16:12:03.240  INFO 6627 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-06-28 16:12:03.240  INFO 6627 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-06-28 16:12:03.241  INFO 6627 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-06-28 16:12:03.798  INFO 6627 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@78dd667e: startup date [Wed Jun 28 16:11:59 CST 2017]; root of context hierarchy
2017-06-28 16:12:03.928  INFO 6627 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String Example.home()
2017-06-28 16:12:03.938  INFO 6627 --- [           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-06-28 16:12:03.944  INFO 6627 --- [           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-06-28 16:12:04.071  INFO 6627 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-28 16:12:04.071  INFO 6627 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-28 16:12:04.115  INFO 6627 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-28 16:12:04.421  INFO 6627 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-06-28 16:12:04.576  INFO 6627 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-28 16:12:04.580  INFO 6627 --- [           main] Example                                  : Started Example in 5.927 seconds (JVM running for 7.945)

 在浏览器输入http://localhost:8080/,便可返回以下信息:

Spring Boot 部署与服务配置

Spring Boot的配置依赖application.properties文件(位于src/main/java/),因此创建该文件。

Server配置

对server的几个常用的配置做个简单说明:
# 项目contextPath,一般在正式发布版本中,我们不配置
server.context-path=/myspringboot
# 错误页,指定发生错误时,跳转的URL。请查看BasicErrorController源码便知
server.error.path=/error
# 服务端口
server.port=9090
# session最大超时时间(分钟),默认为30
server.session-timeout=60
# 该服务绑定IP地址,启动服务器时如本机不是该IP地址则抛出异常启动失败,只有特殊需求的情况下才配置
# server.address=192.168.16.11

 Tomcat配置

Tomcat为Spring Boot的默认容器,下面是几个常用配置:

# tomcat最大线程数,默认为200
server.tomcat.max-threads=800
# tomcat的URI编码
server.tomcat.uri-encoding=UTF-8
# 存放Tomcat的日志、Dump等文件的临时文件夹,默认为系统的tmp文件夹(如:C:\Users\Shanhy\AppData\Local\Temp)
server.tomcat.basedir=H:/springboot-tomcat-tmp
# 打开Tomcat的Access日志,并可以设置日志格式的方法:
#server.tomcat.access-log-enabled=true
#server.tomcat.access-log-pattern=
# accesslog目录,默认在basedir/logs
#server.tomcat.accesslog.directory=
# 日志文件目录
logging.path=H:/springboot-tomcat-tmp
# 日志文件名称,默认为spring.log
logging.file=myapp.log

使用Profile区分环境

spring boot 可以在 “配置文件”、“Java代码类”、“日志配置” 中来配置profile区分不同环境执行不同的结果

配置文件

以application.properties 为例,通过文件名来区分环境 application-{profile}.properties

创建application.properties文件

app.name=MyApp
server.port=8080

创建application-dev.properties文件:

server.port=8081

 创建application-stg.properties文件:

server.port=8082

在启动程序的时候通过添加 –spring.profiles.active={profile} 来指定具体使用的配置
例如我们执行 java -jar demo.jar –spring.profiles.active=dev 那么上面3个文件中的内容将被如何应用?
Spring Boot 会先加载默认的配置文件,然后使用具体指定的profile中的配置去覆盖默认配置。

在Eclipse中的Boot DashBoard中,启动应用之前可以通过配置选择指定的配置文件,如下:

右击工程:

点击Open Config

在Profile选项里选择对应的参数stg或dev便可以选择不同的配置文件。

创建可执行jar文件

在项目所在目录执行gradle build即可,会在build/libs目录下生成对应的jar文件。

注意:打包时配置文件并不会被打包,因此需要在build.gradle文件中加上以下内容:

jar.into('/') {  
    from('src/main/java')  
}  

目的是将src/main/java目录下的所有文件拷贝到jar包运行的根目录(class类所在的目录),jar包的类和配置文件被放到/BOOT-INF/classes/目录下。如下图:

运行jar文件

java -jar myproject-0.0.1.jar -D spring.profiles.active=dev 

其中参数-D spring.profiles.active=dev用来指定具体的配置文件application-dev.properties

输出以下信息:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2017-06-28 17:35:59.108  INFO 11216 --- [           main] Example                                  : Starting Example on wuchao-Lenovo with PID 11216 (/home/wuchao/eclipse-jee/workspace/GradleProject_02/build/libs/myproject-0.0.1.jar started by wuchao in /home/wuchao/eclipse-jee/workspace/GradleProject_02/build/libs)
2017-06-28 17:35:59.119  INFO 11216 --- [           main] Example                                  : The following profiles are active: dev
2017-06-28 17:35:59.186  INFO 11216 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4534b60d: startup date [Wed Jun 28 17:35:59 CST 2017]; root of context hierarchy
2017-06-28 17:36:01.151  INFO 11216 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8081 (http)
2017-06-28 17:36:01.171  INFO 11216 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-06-28 17:36:01.172  INFO 11216 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
2017-06-28 17:36:01.273  INFO 11216 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-06-28 17:36:01.273  INFO 11216 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2090 ms
2017-06-28 17:36:01.426  INFO 11216 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-06-28 17:36:01.430  INFO 11216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-06-28 17:36:01.431  INFO 11216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-06-28 17:36:01.431  INFO 11216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-06-28 17:36:01.431  INFO 11216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-06-28 17:36:01.957  INFO 11216 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4534b60d: startup date [Wed Jun 28 17:35:59 CST 2017]; root of context hierarchy
2017-06-28 17:36:02.048  INFO 11216 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String Example.home()
2017-06-28 17:36:02.054  INFO 11216 --- [           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-06-28 17:36:02.055  INFO 11216 --- [           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-06-28 17:36:02.100  INFO 11216 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-28 17:36:02.101  INFO 11216 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-28 17:36:02.157  INFO 11216 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-28 17:36:02.346  INFO 11216 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-06-28 17:36:02.415  INFO 11216 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8081 (http)
2017-06-28 17:36:02.420  INFO 11216 --- [           main] Example                                  : Started Example in 3.838 seconds (JVM running for 4.389)

 便可在浏览器中输入http://localhost:8081/访问该应用。

 

posted @ 2017-06-28 17:39  且听风吟-wuchao  阅读(2089)  评论(0编辑  收藏  举报