IDE軟件:IntelliJ IDEA 15.0.2
操作系統(tǒng):Win10
Spring boot版本:1.4.1 Release
Maven版本:apache-maven-3.5.2
一、Maven工程創(chuàng)建
??使用Maven新建一個(gè)項(xiàng)目主要有以下三個(gè)步驟:
??1.選擇項(xiàng)目類型 在Project SDK下拉列表框中選擇前面安裝的Java 1.8,如果下拉列表框中不存在Java 1.8,可以單擊New按鈕,找到安裝Java的位置,選擇它。然后在左面?zhèn)冗厵诘捻?xiàng)目類型中,選擇Maven項(xiàng)目,即可使用Maven作為項(xiàng)目的管理工具。至于Maven中的archetype,因?yàn)槲覀儾⒉淮蛩闶褂闷渲腥魏我环N類型,所以不用勾選,然后單擊Next進(jìn)入下一步。





二、POM文件配置,添加spring boot支持
??使用Maven,通過導(dǎo)入Spring Boot的starter模塊,可以將許多程序依賴包自動(dòng)導(dǎo)入工程中。使用Maven的parent POM,還可以更容易地管理依賴的版本和使用默認(rèn)的配置,工程中的模塊也可以很方便地繼承它。修改pom.xml文件,為一個(gè)使用Spring Boot開發(fā)框架的Web項(xiàng)目開發(fā)提供所需的相關(guān)依賴。


三、Spring boot案例代碼編寫
??Spring Boot的官方文檔中提供了一個(gè)最簡單的Web實(shí)例程序,實(shí)例只使用了幾行代碼,雖然簡單,但實(shí)際上這已經(jīng)可以算作是一個(gè)完整的Web項(xiàng)目。
package springboot.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication @RestController
public class Application {
@RequestMapping("/")
String home() {
return "hello";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
??這個(gè)簡單實(shí)例,首先是一個(gè)Spring Boot應(yīng)用的程序入口,或者叫作主程序,其中使用了一個(gè)注解@SpringBootApplication來標(biāo)注它是一個(gè)Spring Boot應(yīng)用,main方法使它成為一個(gè)主程序,將在應(yīng)用啟動(dòng)時(shí)首先被執(zhí)行。其次,注解@RestController同時(shí)標(biāo)注這個(gè)程序還是一個(gè)控制器,如果在瀏覽器中訪問應(yīng)用的根目錄,它將調(diào)用home方法,并輸出字符串:hello。
四、運(yùn)行Spring boot工程
??選擇Run或Debug運(yùn)行hello配置項(xiàng)目。如果啟動(dòng)成功,將在控制臺(tái)中輸出類似如下信息:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.1.RELEASE)
2018-02-09 11:13:14.367 INFO 11580 --- [ main] springboot.example.Application : Starting Application on DESKTOP-9DOM5PD with PID 11580 (C:\Users\zhang\IdeaProjects\spring-boot-hello\target\classes started by zhang in C:\Users\zhang\IdeaProjects\spring-boot-hello)
2018-02-09 11:13:14.371 INFO 11580 --- [ main] springboot.example.Application : No active profile set, falling back to default profiles: default
2018-02-09 11:13:14.501 INFO 11580 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@21de60b4: startup date [Fri Feb 09 11:13:14 CST 2018]; root of context hierarchy
2018-02-09 11:13:16.674 INFO 11580 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-02-09 11:13:16.692 INFO 11580 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2018-02-09 11:13:16.693 INFO 11580 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.5
2018-02-09 11:13:16.849 INFO 11580 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-02-09 11:13:16.849 INFO 11580 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2353 ms
2018-02-09 11:13:17.043 INFO 11580 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-02-09 11:13:17.048 INFO 11580 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-09 11:13:17.048 INFO 11580 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-09 11:13:17.048 INFO 11580 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-09 11:13:17.048 INFO 11580 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-09 11:13:17.402 INFO 11580 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@21de60b4: startup date [Fri Feb 09 11:13:14 CST 2018]; root of context hierarchy
2018-02-09 11:13:17.527 INFO 11580 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String springboot.example.Application.home()
2018-02-09 11:13:17.532 INFO 11580 --- [ 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)
2018-02-09 11:13:17.532 INFO 11580 --- [ 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)
2018-02-09 11:13:17.566 INFO 11580 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-09 11:13:17.566 INFO 11580 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-09 11:13:17.653 INFO 11580 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-02-09 11:13:17.916 INFO 11580 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-02-09 11:13:17.974 INFO 11580 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-02-09 11:13:17.979 INFO 11580 --- [ main] springboot.example.Application : Started Application in 4.59 seconds (JVM running for 5.223)
2018-02-09 11:13:45.405 INFO 11580 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-02-09 11:13:45.405 INFO 11580 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-02-09 11:13:45.429 INFO 11580 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 24 ms
??從上面的輸出中可以看出,Tomcat默認(rèn)開啟了8080端口。要訪問這個(gè)應(yīng)用提供的服務(wù),可以在瀏覽器的地址欄中輸入http://localhost:8080/ 。這樣就可以看到我們期望的輸出字符:hello。

五、項(xiàng)目發(fā)布
??上面操作演示了在IDEA環(huán)境中如何運(yùn)行一個(gè)應(yīng)用。如果我們想把應(yīng)用發(fā)布出去,可以將Maven配置增加一個(gè)發(fā)布插件來實(shí)現(xiàn)。如代碼所示,增加了一個(gè)打包插件:spring-boot-maven-plugin,并增加了一行打包的配置:<packaging>jar</packaging>,這行配置指定將應(yīng)用工程打包成jar文件。
<?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
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springboot.example</groupId>
<artifactId>spring-boot-hello</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
??這樣就可以在IDEA中增加一個(gè)打包的配置,打開Run/Debug Configurations對(duì)話框,選擇增加配置一個(gè)Maven打包項(xiàng)目,在工作目錄中選擇工程所在根目錄,在命令行中輸入package,并將配置保存為mvn,如圖所示。

??運(yùn)行mvn打包項(xiàng)目,就可以將實(shí)例工程打包,打包的文件將輸出在工程的target目錄中。 如圖:

??控制臺(tái)提示如下:
"C:\Program Files\Java\jdk1.8.0_144\bin\java" "-Dmaven.home=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 15.0.2\plugins\maven\lib\maven3" "-Dclassworlds.conf=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 15.0.2\plugins\maven\lib\maven3\bin\m2.conf" -Didea.launcher.port=7534 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 15.0.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\JetBrains\IntelliJ IDEA 15.0.2\plugins\maven\lib\maven3\boot\plexus-classworlds-2.4.jar;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 15.0.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain org.codehaus.classworlds.Launcher -Didea.version=15.0.2 package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring-boot-hello 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ spring-boot-hello ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ spring-boot-hello ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ spring-boot-hello ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\zhang\IdeaProjects\spring-boot-hello\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ spring-boot-hello ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ spring-boot-hello ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ spring-boot-hello ---
[INFO]
[INFO] --- spring-boot-maven-plugin:1.4.1.RELEASE:repackage (default) @ spring-boot-hello ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.150s
[INFO] Finished at: Fri Feb 09 12:19:37 CST 2018
[INFO] Final Memory: 14M/157M
[INFO] ------------------------------------------------------------------------
Process finished with exit code 0
??如果希望將工程發(fā)布成war文件,應(yīng)當(dāng)將pom.xml的Maven配置<packaging>jar</packaging> 改成 <packaging>war</packaging>,這樣就可以打包成war文件。打包完成后將war文件放置在Tomcat的webapp路徑中,啟動(dòng)Tomcat就能自動(dòng)運(yùn)行程序。 這里需要注意的是,如果使用自己配置的Tomcat運(yùn)行應(yīng)用,在安裝JDK時(shí)必須配置JAVA_HOME環(huán)境變量,同時(shí)JDK要求1.8以上的版本,Tomcat必須是8.0以上的版本。
六、關(guān)于spring boot配置
??關(guān)于Spring Boot配置,可以在工程的resources文件夾中創(chuàng)建一個(gè)application.properties或application.yml文件,這個(gè)文件會(huì)被發(fā)布在classpath中,并且被Spring Boot自動(dòng)讀取。這里推薦使用application.yml文件,因?yàn)樗峁┝私Y(jié)構(gòu)化及其嵌套的格式,例如,可以按如下所示配置上面的工程,將默認(rèn)端口改為80,并且將Tomcat的字符集定義為UTF-8。
server:
port: 80
tomcat:
uri-encoding: UTF-8
??如果要使用application.properties文件,上面的配置就要改成如下所示的樣子,其結(jié)果完全相同。
server.port = 80
server.tomcat.uri-enconding = UTF-8
??使用這個(gè)配置文件可以直接使用Spring Boot預(yù)定義的一些配置參數(shù),關(guān)于其他配置參數(shù)的詳細(xì)說明和描述可以查看官方的文檔說明:https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html 。
七、總結(jié)
??Spring Boot開發(fā)框架是一個(gè)非常輕量級(jí)的開發(fā)框架,所以也有人把它叫作微框架,使用Spring Boot框架開發(fā)應(yīng)用不但入門容易,而且其蘊(yùn)藏的無比強(qiáng)大的功能,使開發(fā)過程也變得更加容易。