Spring Boot快速起步。至于什么是Spring Boot?它能干些什么,我在这里不解释,想了解的朋友可以去网站自行搜索,相信你会明白。

 

 

好了,废话不多说,直接开始。

一、起步

1、创建一个普通的Maven项目

此处省略N个姿势……
2、修改pox.xml,添加Spring Boot的相关依赖

<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>com.bkybk</groupId>
  <artifactId>boot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>boot</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

	<!-- Inherit defaults from Spring Boot -->  
	<parent>  
	    <groupId>org.springframework.boot</groupId>  
	    <artifactId>spring-boot-starter-parent</artifactId>  
	    <version>1.5.6.RELEASE</version>  
	</parent>  
  
	<!-- Add typical dependencies for a web application -->  
	<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>  
  
	<!-- Package as an executable JAR -->  
	<build>  
	    <plugins>  
	        <plugin>  
	            <groupId>org.springframework.boot</groupId>  
	            <artifactId>spring-boot-maven-plugin</artifactId>  
	        </plugin>  
	    </plugins>  
	</build>  
  
	<!-- 允许访问Spring里程碑和快照 -->  
	<!-- (如果您在0.5.0.RELEASE之后使用任何内容,则不需要此操作) -->  
	<!-- <repositories>  
	    <repository>  
	        <id>spring-snapshots</id>  
	        <url>http://repo.spring.io/snapshot</url>  
	        <snapshots><enabled>true</enabled></snapshots>  
	    </repository>  
	    <repository>  
	        <id>spring-milestones</id>  
	        <url>http://repo.spring.io/milestone</url>  
	        <snapshots><enabled>true</enabled></snapshots>  
	    </repository>  
	</repositories> -->  
	<!-- <pluginRepositories>  
	    <pluginRepository>  
	        <id>spring-snapshots</id>  
	        <url>http://repo.spring.io/snapshot</url>  
	    </pluginRepository>  
	    <pluginRepository>  
	        <id>spring-milestones</id>  
	        <url>http://repo.spring.io/milestone</url>  
	    </pluginRepository>  
	</pluginRepositories> -->  
  
</project>

3、修改或创建App.java

package com.bkybk.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Hello world!
 *
 */
@Configuration  
@ComponentScan  
@EnableAutoConfiguration 
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class); 
    }
}

 

4、创建HelloController.java

package com.bkybk.boot;

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

@RestController
public class HelloController {
    
    @RequestMapping("/")
    public String index() {
        return "Hello,Spring boot!";
    }
}

运行App的main方法,启动Spring Boot

微笑:“完美~ ”

二、单元测试
1、pox.xml

<!-- 增加单元测试的依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2、创建HelloTest

package com.bkybk.boot.test;


import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes=App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloTest {

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void greetingShouldReturestTemplaternDefaultMessage() throws Exception {
        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/",
                String.class)).contains("Hello,Spring boot!");
    }
}

运行jUnit Test,单元测试运行OK

再次微笑:“完美~ ”

三:So,怎么部署spring boot?
1、给运行机器搭建并配置Maven
此处省略一万个精彩动作和激情画面……

安装并配置完成Maven,查看Maven版本:

E:\workspace\boot>mvn -v
Apache Maven 3.0.4 (r1232337; 2012-01-17 16:44:56+0800)
Maven home: D:\Develop\Maven\apache-maven-3.0.4\bin\..
Java version: 1.8.0_121, vendor: Oracle Corporation
Java home: D:\Develop\Java\jdk1.8.0_121\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos"
E:\workspace\boot>

2、开始打包

打包命令:mvn package
如果在打包的时候要跳过自己项目中的一些测试,则添加参数 -DskipTests

E:\workspace\boot>mvn package -DskipTests
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building boot 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ boot ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory E:\workspace\boot\src\main\resources
[INFO] skip non existing resourceDirectory E:\workspace\boot\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ boot ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ boot ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory E:\workspace\boot\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ boot ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to E:\workspace\boot\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ boot ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ boot ---
[INFO] Building jar: E:\workspace\boot\target\boot-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.6.RELEASE:repackage (default) @ boot ---
Downloading: http://192.168.1.180:8081/content/groups/public/org/codehaus/plexus/plexus-classworlds/2.4/plexus-classworlds-2.4.pom
Downloaded: http://192.168.1.180:8081/content/groups/public/org/codehaus/plexus/plexus-classworlds/2.4/plexus-classworlds-2.4.pom (0 B at 0.0 KB/sec)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.675s
[INFO] Finished at: Tue Sep 19 18:08:20 CST 2017
[INFO] Final Memory: 32M/277M
[INFO] ------------------------------------------------------------------------
E:\workspace\boot>

打包完成在target下面就会有boot-0.0.1-SNAPSHOT.jar这样的jar,打包完成

3、在CMD中执行命令“java -jar file”,file就是刚刚打好的包

E:\workspace\boot>java -jar target/boot-0.0.1-SNAPSHOT.jar

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

2017-09-19 18:20:12.072  INFO 10508 --- [           main] com.bkybk.boot.test.App                  : Starting App v0.0.1-SNAPSHOT on lenovo-PC with PID 10508 (E:\workspace\boot\target\boot-0.0.1-SNAPSHOT.jar started by lenovo in E:\workspace\boot)
2017-09-19 18:20:12.085  INFO 10508 --- [           main] com.bkybk.boot.test.App                  : No active profile set, falling back to default profiles: default
2017-09-19 18:20:12.167  INFO 10508 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@443b7951: startup date [Tue Sep 19 18:20:12 CST 2017]; root of context hierarchy
2017-09-19 18:20:14.503  INFO 10508 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-09-19 18:20:14.520  INFO 10508 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-09-19 18:20:14.523  INFO 10508 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-09-19 18:20:14.654  INFO 10508 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-09-19 18:20:14.654  INFO 10508 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2490 ms
2017-09-19 18:20:14.830  INFO 10508 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-19 18:20:14.843  INFO 10508 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-19 18:20:14.849  INFO 10508 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-19 18:20:14.853  INFO 10508 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-19 18:20:14.855  INFO 10508 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-19 18:20:15.243  INFO 10508 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@443b7951: startup date [Tue Sep 19 18:20:12 CST 2017]; root of context hierarchy
2017-09-19 18:20:15.366  INFO 10508 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.bkybk.boot.test.HelloController.index()
2017-09-19 18:20:15.372  INFO 10508 --- [           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-09-19 18:20:15.373  INFO 10508 --- [           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-09-19 18:20:15.422  INFO 10508 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-19 18:20:15.422  INFO 10508 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-19 18:20:15.463  INFO 10508 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-19 18:20:15.618  INFO 10508 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-09-19 18:20:15.710  INFO 10508 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-09-19 18:20:15.720  INFO 10508 --- [           main] com.bkybk.boot.test.App                  : Started App in 4.067 seconds (JVM running for 4.596)
2017-09-19 18:20:30.485  INFO 10508 --- [       Thread-3] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@443b7951: startup date [Tue Sep 19 18:20:12 CST 2017]; root of context hierarchy

这时程序就部署好了,有没有感觉So Easy?是不是炒鸡简单?

标签: Spring Boot, Spring Boot 起步, Spring Boot 快速入门

添加新评论