A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 欢迎光临 于 2018-3-30 15:00 编辑

SpringBoot项目搭建及HelloWorld入门
在过去, 基于Spring框架开发的程序, 通常都需要很多配置, 而这些配置通常都是模板式的, 重复且繁琐. 为了简化开发, Spring团队提供了Spring Boot开发方式, 它的目的就是为了简化Spring开发, 采用"约定大于配置"的方式, 来简化项目搭建时的配置.
Spring Boot项目采用"约定大于配置"的理念, 它把常用的应用开发依赖组合成一个Maven依赖, 默认包含了相关组件的配置, 达到上手即用的目的. 此外, Spring Boot在开发Web项目时, 内置了Web容器, 在项目编写完毕后, 项目可以打包为.jar包, 可以直接运行, 内部包含了Web容器, 从而简化了项目的部署.
下面我们就从创建项目到打包运行, 来体验一下Spring Boot的开发方式.

创建Spring Boot项目
Spring Boot官方提供了很多项目脚手架, 也就是说针对不同的应用, 提供了对应的项目结构, 我们只需要选择对应的项目结构即可.
创建项目并指定脚手架的方式有2种:

  • 官网的Spring Initializr方式
  • IDEA中使用Spring Initializr方式

两种方式的效果一样, 区别是第1种从页面生成项目并下载, 第2种是直接在IDEA中操作. 下面演示第2种方式.

IDEA内置Spring Initializr方式
打开IDEA, 选择Create New Project

选择Spring Initializr. 右侧URL默认选择https://start.spring.io, 点击Next


在Group输入项目的包名, 在Artifact输入项目名, 打包方式为Jar, 点击Next


我们要创建一个Web项目. 所以选择Web, 勾选右侧的Web, 默认会提供Tomcat和SpringMVC的依赖. 点击Next


在Project Name中输入项目的名称. 点击Finish


项目会自动下载脚手架, 并构建. 构建完毕的项目结构如下:


其中HelloSpringApplication中的main()方法就是程序的启动入口

Spring Boot项目的POM依赖
以下是创建项目后自动生成的pom.xml. 从中可以看出, Spring Boot项目依赖一个名为spring-boot-starter-parent的父项目, 提供了Spring Boot共性的内容, 而我们创建的项目应用于Web, 需要具备SpringMVC的功能, 所以项目依赖中有spring-boot-starter-web

[XML] 纯文本查看 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<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 [url]http://maven.apache.org/xsd/maven-4.0.0.xsd[/url]">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.itheima</groupId>
	<artifactId>hello-spring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>hello-spring</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

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

</project>


编写Hello World程序
下面我们编写一个简单的Web项目, 实现浏览器访问根路径显示"Hello Spring Boot!"文字

创建Controller
步骤:
  • 创建HelloController类, 并为类添加@RestController注解, 表示该Controller用于处理REST请求
  • 定义public String hello()方法, 并为方法添加@RequestMapping(value = "/", method = RequestMethod.GET)注解, 在方法中返回Hello Spring Boot!字符串. 表示该方法处理根路径的GET访问, 并返回该字符串


[Java] 纯文本查看 复制代码
package com.itheima.hellospring;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String hello() {
        return "Hello Spring Boot!";
    }
}

有了Controller我们就可以实现简单的Web请求处理.

启动项目
代码编写完毕后就可以运行项目了. Spring Boot只需要生成jar包运行即可, jar包中内置Tomcat, 不再需要单独打war包放入Tomcat.
我们可以有2种方式运行程序:

  • IDEA界面运行方式
  • Maven命令方式

IDEA界面运行方式

在HelloSpringApplication类中, 鼠标右键, 选择Run 'HelloSpringApplication'.


控制台将会输出运行信息:

[Bash shell] 纯文本查看 复制代码
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.0.RELEASE)

2018-03-28 23:09:20.522  INFO 44988 --- [           main] c.i.hellospring.HelloSpringApplication   : Starting HelloSpringApplication on lishaoqing with PID 44988 (D:\my\dev\web\hello-spring\target\classes started by lishaoqing in D:\my\dev\web\hello-spring)
2018-03-28 23:09:20.528  INFO 44988 --- [           main] c.i.hellospring.HelloSpringApplication   : No active profile set, falling back to default profiles: default
2018-03-28 23:09:20.587  INFO 44988 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@1c153a1: startup date [Wed Mar 28 23:09:20 CST 2018]; root of context hierarchy
2018-03-28 23:09:21.550  INFO 44988 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-03-28 23:09:21.569  INFO 44988 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-03-28 23:09:21.569  INFO 44988 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-03-28 23:09:21.572  INFO 44988 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [D:\develop\jdk8\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;D:\develop\jdk7\bin;D:\develop\curl;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;D:\develop\mysql55\bin;D:\develop\nodejs\;C:\Users\lishaoqing\AppData\Local\Microsoft\WindowsApps;;D:\develop\vscode\bin;D:\develop\fiddler;C:\Users\lishaoqing\AppData\Roaming\npm;D:\develop\babun\.babun;.]
2018-03-28 23:09:21.645  INFO 44988 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-03-28 23:09:21.645  INFO 44988 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1062 ms
2018-03-28 23:09:21.767  INFO 44988 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-03-28 23:09:21.770  INFO 44988 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-28 23:09:21.771  INFO 44988 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-28 23:09:21.771  INFO 44988 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-28 23:09:21.771  INFO 44988 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-03-28 23:09:22.070  INFO 44988 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@1c153a1: startup date [Wed Mar 28 23:09:20 CST 2018]; root of context hierarchy
2018-03-28 23:09:22.118  INFO 44988 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String com.itheima.hellospring.HelloController.hello()
2018-03-28 23:09:22.124  INFO 44988 --- [           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.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-28 23:09:22.124  INFO 44988 --- [           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.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-28 23:09:22.154  INFO 44988 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-28 23:09:22.154  INFO 44988 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-28 23:09:22.184  INFO 44988 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-28 23:09:22.375  INFO 44988 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-03-28 23:09:22.413  INFO 44988 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-03-28 23:09:22.416  INFO 44988 --- [           main] c.i.hellospring.HelloSpringApplication   : Started HelloSpringApplication in 2.294 seconds (JVM running for 3.134)

信息中显示: Tomcat started on port(s): 8080 (http) with context path ''. 我们访问http://localhost:8080即可看到页面
Maven命令方式
我们也可以使用mvn命令在命令行启动程序:

[Bash shell] 纯文本查看 复制代码
# 启动Spring Boot程序
mvn spring-boot:run


启动效果和图形界面操作一致, 不再演示.

小结
以上就是利用Spring Boot创建并完成Web操作的步骤. 从中可以看出, Spring Boot极大的简化了配置, 我们并没有创建任何的配置文件, 就可以使用SpringMVC和Tomcat实现Web应用. 这一切是因为Spring Boot采用"约定大于配置"的理念, 如果我们没有配置, 则采用默认自带的配置. 这对于项目开发的效率有着极大的提升.

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马