Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員再也不須要定義樣板化的配置。經過這種方式,Spring Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成爲領導者。html
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.cpt</groupId> <artifactId>SpringBoot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SpringBoot Maven Webapp</name> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.5.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <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> </plugin> </plugins> </build> </project>
二、保存以後靜靜等待依賴包下載完畢,接下來建立一個java類,java
在src/main/java下建立一個TestSpringBoot.java類,裏面添加代碼以下:web
package controller;
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 TestSpringBoot {
@RequestMapping("/")
public String firstSpringBoot() {
return "Hello World!";
}
public static void main(String[] args){
SpringApplication.run(TestSpringBoot.class, args);
}
}
三、直接運行main方法;它會啓動內置的tomcat服務:啓動後以下所示:spring
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.2.5.RELEASE) 2018-01-17 16:20:06.722 INFO 6028 --- [ main] controller.TestSpringBoot : Starting TestSpringBoot on 0DYF9DI9DPNWES6 with PID 6028 (started by Administrator in D:\Softwarefolder\IDE\MyEclipse\WorkSpace\SSM\SpringBoot Maven Webapp) 2018-01-17 16:20:06.831 INFO 6028 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5fd91a7a: startup date [Wed Jan 17 16:20:06 CST 2018]; root of context hierarchy 2018-01-17 16:20:08.077 INFO 6028 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]] 2018-01-17 16:20:09.743 INFO 6028 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 9000 (http) 2018-01-17 16:20:10.247 INFO 6028 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat 2018-01-17 16:20:10.249 INFO 6028 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.23 2018-01-17 16:20:10.485 INFO 6028 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2018-01-17 16:20:10.485 INFO 6028 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3659 ms 2018-01-17 16:20:11.820 INFO 6028 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2018-01-17 16:20:11.827 INFO 6028 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2018-01-17 16:20:11.827 INFO 6028 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2018-01-17 16:20:12.187 INFO 6028 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5fd91a7a: startup date [Wed Jan 17 16:20:06 CST 2018]; root of context hierarchy 2018-01-17 16:20:12.343 INFO 6028 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String controller.TestSpringBoot.firstSpringBoot() 2018-01-17 16:20:12.344 INFO 6028 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[GET]}" onto public java.lang.String controller.TestSpringBoot.loginGet() 2018-01-17 16:20:12.344 INFO 6028 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[POST]}" onto public java.lang.String controller.TestSpringBoot.loginPost() 2018-01-17 16:20:12.348 INFO 6028 --- [ 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-01-17 16:20:12.348 INFO 6028 --- [ 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) 2018-01-17 16:20:12.407 INFO 6028 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-01-17 16:20:12.407 INFO 6028 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-01-17 16:20:12.482 INFO 6028 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-01-17 16:20:12.619 INFO 6028 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2018-01-17 16:20:12.747 INFO 6028 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 9000 (http) 2018-01-17 16:20:12.750 INFO 6028 --- [ main] controller.TestSpringBoot : Started TestSpringBoot in 6.666 seconds (JVM running for 7.24)
三、在網頁上可輸入地址localhost:8080/便可訪問到firstSpringBoot()方法,在頁面上顯示Hello word,apache
(若是報錯端口被佔用的話能夠修改內置Tomcat的端口,詳情鏈接 http://www.cnblogs.com/caopt/p/8303662.html)api
四、這是一個簡單應用程序,但是爲何它運行main方法就能夠了呢,讓咱們從源碼分析一下:瀏覽器
運行main方法以後 SpringApplication會運行他的run方法,看下源碼tomcat
/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified source using default settings.
* @param source the source to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Object source, String... args) {
return run(new Object[] { source }, args);
}
/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified sources using default settings and user supplied arguments.
* @param sources the sources to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
return new SpringApplication(sources).run(args);
}
一、它根據傳過來的類會建立一個Spring應用上下文(Application Context)(經過映射的方式找到要找的東西)。另外一方面它會掃描當前應用類路徑上的依賴,例如本例中發現spring-webmvc
(由 spring-boot-starter-web
傳遞引入)在類路徑中,那麼Spring Boot會判斷這是一個Web應用,並啓動一個內嵌的Servlet容器(默認是Tomcat)用於處理HTTP請求。mvc
@Controller
類進行處理,
@RestController
是一類特殊的
@Controller
,它的返回值直接做爲HTTP Response的Body部分返回給瀏覽器。
package controller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class TestSpringBoot {
@RequestMapping(value = "/TestGet", method = RequestMethod.GET)
public String testGet() {
return "Hello Get";
}
@RequestMapping(value = "/TestPost", method = RequestMethod.POST)
public String testPost() {
return "Hello Post";
}
@RequestMapping("/")
public String firstSpringBoot() {
return "Hello World!";
}
public static void main(String[] args){
SpringApplication.run(TestSpringBoot.class, args);
}
}
四、springBoot對調試支持很好,修改以後能夠實時生效,須要添加如下的配置:app
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build>
這裏須要注意的是,版本要匹配否則會報錯。