1.新建了一個SpringBoot項目:只引用需要用到的spring boot相關的jar包,除此之外沒有任何的配置
啟動application.java報錯:
***************************
不用數據庫相關的東西 就不要在pom中引入相關依賴。

2.新建一個小項目,springboot使用1.5.16,項目啟動類使用注解@SpringBootApplication,controller使用注解@Controller,瀏覽器輸入ip地址報錯:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
控制器的URL路徑沒有找到
@controller改成@RestController頁面可正常顯示
3.pom.xml中配置了熱啟動,但是修改controller后沒有重新加載,console控制台也沒有加載新的內容-》熱啟動沒有生效

查找原因:熱部署依賴於項目的自動編譯功能:Project->Build Automatically(自動編譯)是否已經勾選,若沒勾選,則需要勾選,否則熱啟動無用
4.SpringBoot項目啟動類*Application.java:SpringBoot項目只能有一個main方法:
其中:@SpringBootApplication 等價於
@Controller
@EnableAutoConfiguration
@ComponentScan("com.yst.helloWOrld.web")

5.Junit單元測試使用MockMvc做controller接口測試
(51)直接返回字符串中含有中文---》中文亂碼
JunitTest代碼為:
1 package com.yst.helloWorld; 2 3 import org.junit.Before; 4 import org.junit.Test; 5 import org.springframework.boot.test.context.SpringBootTest; 6 import org.springframework.test.web.servlet.MockMvc; 7 import org.springframework.test.web.servlet.MvcResult; 8 import org.springframework.test.web.servlet.ResultHandler; 9 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 10 import org.springframework.test.web.servlet.setup.MockMvcBuilders; 11 import com.yst.helloWorld.web.HelloWorldController; 12 13 @SpringBootTest 14 public class HelloWorldApplicationTests { 15 //使用MockMvc做controller接口測試 16 private MockMvc mockMvc; 17 18 @Before //這個方法在每個方法執行之前都會執行一遍 19 public void setUp() throws Exception { 20 mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build(); 21 } 22 @Test 23 public void getHello() throws Exception { 24 mockMvc.perform(MockMvcRequestBuilders.post("/hello")//請求的url,請求的方法是post 25 // .contentType(MediaType.APPLICATION_FORM_URLENCODED) 26 // .param("name", "value")//添加參數 27 ).andDo(new ResultHandler() { 28 @Override 29 public void handle(MvcResult result) throws Exception { 30 result.getResponse().setCharacterEncoding("UTF-8"); 31 System.out.println("結果:"+result.getResponse().getContentAsString());//result.getResponse().getContentAsString()不支持中文格式 32 System.out.println("請求狀態碼:"+result.getResponse().getStatus());//result.getResponse().getContentAsString()不支持中文格式 33 } 34 }); 35 } 36 37 // @Test 38 // public void hello() { 39 // System.out.println("hello"); 40 // } 41 // @Test 42 // public void contextLoads() { 43 // } 44 45 }
controller代碼:
1 package com.yst.helloWorld.web; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.ui.Model; 5 import org.springframework.web.bind.annotation.PathVariable; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.RequestMethod; 8 import org.springframework.web.bind.annotation.RestController; 9 @RestController 10 //@Controller 11 public class HelloWorldController { 12 13 @RequestMapping(value="/hello") 14 public String hello() { 15 return "hello my world! 我的世界"; 16 } 17 18 @RequestMapping(value="/findUser/{userId}") 19 public String findUser(@PathVariable String userId, Model model) { 20 return "my User:"+userId; 21 } 22 23 @RequestMapping(value="/{textualPart:[a-z-]+}.{numericPart:[\\d]+}") 24 public String regularExpression( 25 @PathVariable String textualPart, 26 @PathVariable String numericPart){ 27 28 System.out.println("Textual part: " + textualPart + 29 ", numeric part: " + numericPart); 30 return "someResult"; 31 } 32 33 @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue") 34 public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { 35 // implementation omitted 36 } 37 38 39 }
執行結果為:
結果:hello my world! ???? ----------》中文顯示正常
請求狀態碼:200
---》解決方式:暫時未解決
(52)返回對象或集合:對象字段含有中文--》返回結果正常顯示
controller代碼:
1 package com.yst.helloWorld.web; 2 3 import org.springframework.ui.Model; 4 import org.springframework.web.bind.annotation.PathVariable; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.RequestMethod; 7 import org.springframework.web.bind.annotation.RestController; 8 9 import com.yst.helloWorld.domain.User; 10 @RestController 11 public class HelloWorldController { 12 13 @RequestMapping("/getUser") 14 public User getUser() { 15 User user = new User(); 16 user.setName("王火火"); 17 user.setAge(18); 18 user.setPass("123456"); 19 return user; 20 21 }
22 }
JunitTest代碼:
1 package com.yst.helloWorld; 2 3 import org.junit.Before; 4 import org.junit.Test; 5 import org.springframework.boot.test.context.SpringBootTest; 6 import org.springframework.test.web.servlet.MockMvc; 7 import org.springframework.test.web.servlet.MvcResult; 8 import org.springframework.test.web.servlet.ResultHandler; 9 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 10 import org.springframework.test.web.servlet.setup.MockMvcBuilders; 11 import com.yst.helloWorld.web.HelloWorldController; 12 13 @SpringBootTest 14 public class HelloWorldApplicationTests { 15 //使用MockMvc做controller接口測試 16 private MockMvc mockMvc; 17 18 @Before //這個方法在每個方法執行之前都會執行一遍 19 public void setUp() throws Exception { 20 mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build(); 21 } 22 23 @Test 24 public void getUser() throws Exception { 25 mockMvc.perform(MockMvcRequestBuilders.post("/getUser"))//請求的url,請求的方法是post 26 .andDo(new ResultHandler() { 27 @Override 28 public void handle(MvcResult result) throws Exception { 29 // result.getResponse().setCharacterEncoding("UTF-8"); 30 System.out.println("結果:"+result.getResponse().getContentAsString());// 31 System.out.println("請求狀態碼:"+result.getResponse().getStatus());// 32 } 33 }); 34 } 35 36 37 38 }
結果為:
結果:{"name":"王火火","age":18,"pass":"123456"} ------》說明SpringBoot自動將對象轉換為Json進行返回
請求狀態碼:200
若返回集合,代碼如下:
1 @RequestMapping("/getUsers") 2 public List<User> getUsers() { 3 List<User> users = new ArrayList<User>(); 4 User u1 = new User(); 5 u1.setName("王火火"); 6 u1.setAge(18); 7 u1.setPass("123456"); 8 users.add(u1); 9 User u2 = new User(); 10 u2.setName("張明"); 11 u2.setAge(18); 12 u2.setPass("123"); 13 users.add(u2); 14 return users; 15 16 }
添加測試方法進行測試,返回內容為:
結果:[{"name":"王火火","age":18,"pass":"123456"},{"name":"張明","age":18,"pass":"123"}]
請求狀態碼:200
so,這說明不管對象/集合/嵌套對象,SpringBoot均可以將其轉換為Json字符串,Spring天然對Json支持;
特別適用於給其他系統提供接口。
6.查看SpringBoot匹配的環境版本:
Spring官網:https://spring.io/--->projects--->Spring boot--->Learn--->選取一個版本,點擊Reference Doc. --->往下拉:查看:
9.System Requirements 和 9.1 Servlet Containers
如圖:

7.限制請求方式:@RequestMapping(method=RequestMethod.POST)
1 @RequestMapping(name = "/getUser",method=RequestMethod.POST)//為安全,只允許post請求訪問 2 public User getUser() { 3 User user = new User(); 4 user.setName("王火火"); 5 user.setAge(18); 6 user.setPass("123456"); 7 return user; 8 }
若以get方式請求,會返回:org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]
8.傳參方式
(1)使用對象接收:適用於從頁面獲取值:頁面中只要是屬於User的屬性都會被自動填充到該對象中
@RequestMapping(name = "/getUser",method=RequestMethod.POST)// public User getUser(User user) { return user; }
(2)適用url進行傳參:@PathVariable(import org.springframework.web.bind.annotation.PathVariable;)
(
注意兩個區別
- @PathVariable是獲取url上數據的。
- @RequestParam獲取請求參數的(包括post表單提交)
)
1 //注意url模板中的占位符的值必須和@PathVariable中的值相同才能完成綁定 2 @RequestMapping(name = "/getUser/{useName}",method=RequestMethod.GET)// 3 public User getUser(@PathVariable String useName) { 4 User user = new User(); 5 user.setName(useName); 6 user.setAge(18); 7 return user; 8 }
然后在瀏覽器輸入地址:http://localhost:8080/getUser/whh ,結果竟然報錯:
報錯:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
1 @RequestMapping(name = "/getUser/{userN}",method=RequestMethod.GET)// 2 public User getUser(@PathVariable("userN") @Valid String useName) { 3 User user = new User(); 4 user.setName(useName); 5 user.setAge(18); 6 return user; 7 }
---->最后終於找到了原因:竟是因為RequestMapping的參數問題:不小心把value寫成了name。 改成value后,瀏覽器頁面返回:
{"name":"whh","age":18,"pass":null}
查看下面源碼可知:name:Assign a name to this mapping.(給這個mapping分配一個名稱),沒有實質性的作用;
類似於注釋,對程序沒什么影響,但是對人友好,因為有些url是拼音的,隔了幾個月沒有注釋的話可能不知道這個url干嗎的
所以,RequestMapping地址進行映射:只能用value或path,不能使用name.
1 @Target({ElementType.METHOD, ElementType.TYPE}) 2 @Retention(RetentionPolicy.RUNTIME) 3 @Documented 4 @Mapping 5 public @interface RequestMapping { 6 7 /** 8 * Assign a name to this mapping. 9 * <p><b>Supported at the type level as well as at the method level!</b> 10 * When used on both levels, a combined name is derived by concatenation 11 * with "#" as separator. 12 * @see org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder 13 * @see org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy 14 */ 15 String name() default ""; 16 17 /** 18 * The primary mapping expressed by this annotation. 19 * <p>In a Servlet environment this is an alias for {@link #path}. 20 * For example {@code @RequestMapping("/foo")} is equivalent to 21 * {@code @RequestMapping(path="/foo")}. 22 * <p>In a Portlet environment this is the mapped portlet modes 23 * (i.e. "EDIT", "VIEW", "HELP" or any custom modes). 24 * <p><b>Supported at the type level as well as at the method level!</b> 25 * When used at the type level, all method-level mappings inherit 26 * this primary mapping, narrowing it for a specific handler method. 27 */ 28 @AliasFor("path") 29 String[] value() default {}; 30 31 /** 32 * In a Servlet environment only: the path mapping URIs (e.g. "/myPath.do"). 33 * Ant-style path patterns are also supported (e.g. "/myPath/*.do"). 34 * At the method level, relative paths (e.g. "edit.do") are supported 35 * within the primary mapping expressed at the type level. 36 * Path mapping URIs may contain placeholders (e.g. "/${connect}"). 37 * <p><b>Supported at the type level as well as at the method level!</b> 38 * When used at the type level, all method-level mappings inherit 39 * this primary mapping, narrowing it for a specific handler method. 40 * @see org.springframework.web.bind.annotation.ValueConstants#DEFAULT_NONE 41 * @since 4.2 42 */ 43 @AliasFor("value") 44 String[] path() default {}; 45 46 /** 47 * The HTTP request methods to map to, narrowing the primary mapping: 48 * GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE. 49 * <p><b>Supported at the type level as well as at the method level!</b> 50 * When used at the type level, all method-level mappings inherit 51 * this HTTP method restriction (i.e. the type-level restriction 52 * gets checked before the handler method is even resolved). 53 * <p>Supported for Servlet environments as well as Portlet 2.0 environments. 54 */ 55 RequestMethod[] method() default {}; 56 57 58 59 }
9.參數校驗依賴於hibernate-validator:見下圖

SpringBoot使用:@Valid(package javax.validation;屬於validation-api-1.1.0.Final.jar)+BindingResult進行參數校驗:代碼如下:
User類:
1 package com.yst.helloWorld.domain; 2 3 import javax.validation.constraints.Max; 4 import javax.validation.constraints.Min; 5 6 import org.hibernate.validator.constraints.Length; 7 import org.hibernate.validator.constraints.NotEmpty; 8 9 public class User { 10 @NotEmpty(message="姓名不能為空") 11 private String name; 12 @Max(value=100,message="年齡不能大於 100 歲") 13 @Min(value=18,message="必須年滿 18 歲") 14 private int age; 15 @NotEmpty(message="密碼不能為空|") 16 @Length(min=6,message="密碼長度不能小於6位") 17 private String pass; 18 //... 19 20 21 }
controller方法:
1 /** 2 * 參數校驗@Valid+BindingResult 3 * 打印錯誤信息 4 * @param user 5 * @param result 6 */ 7 @RequestMapping("/saveUser") 8 public void saveUser(@Valid User user,BindingResult result) { 9 System.out.println("user:"+user); 10 if(result.hasErrors()) { 11 List<ObjectError> list = result.getAllErrors(); 12 for (ObjectError error : list) { 13 System.out.println(error.getCode()+"-"+error.getDefaultMessage()); 14 } 15 } 16 }
測試方法:
1 @Test 2 public void saveUser() throws Exception { 3 mockMvc.perform(MockMvcRequestBuilders.post("/saveUser")//請求的url,請求的方法是post 4 .param("name", "")//添加參數 5 .param("age", "222")//添加參數 6 .param("pass", "123")//添加參數 7 ).andDo(new ResultHandler() { 8 @Override 9 public void handle(MvcResult result) throws Exception { 10 System.out.println("結果:"+result.getResponse().getContentAsString()); 11 System.out.println("請求狀態碼:"+result.getResponse().getStatus()); 12 } 13 }); 14 }
結果返回:
user:com.yst.helloWorld.domain.User@119cbf96
Max-年齡不能大於 100 歲
NotEmpty-姓名不能為空
Length-密碼長度不能小於6位
結果顯示已經觸發了校驗規則,返回了錯誤信息。實際項目開發中可以對錯誤信息進行包裝,返回前端頁面展示。
10.自定義資源文件Property:代碼如下
application.properties:
1 #application.properties 2 com.whh.title=whh 3 com.whh.description=分享技術和生活
自定義配置類:
1 package com.yst.helloWorld.domain; 2 3 import org.springframework.beans.factory.annotation.Value; 4 import org.springframework.stereotype.Component; 5 @Component 6 public class WhhProperties { 7 @Value("${com.whh.title}") 8 private String title; 9 @Value("${com.whh.description}") 10 private String description; 11 public String getTitle() { 12 return title; 13 } 14 public void setTitle(String title) { 15 this.title = title; 16 } 17 public String getDescription() { 18 return description; 19 } 20 public void setDescription(String description) { 21 this.description = description; 22 } 23 24 25 26 }
單元測試代碼:
1 package com.yst.helloWorld; 2 3 import javax.annotation.Resource; 4 5 import org.junit.Test; 6 import org.junit.runner.RunWith; 7 import org.springframework.boot.test.context.SpringBootTest; 8 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 9 import org.springframework.test.context.junit4.SpringRunner; 10 import com.yst.helloWorld.domain.WhhProperties; 11 //@RunWith:運行器,讓測試運行於Spring環境; 12 //@RunWith(SpringRunner.class)=@RunWith(SpringJUnit4ClassRunnerRunner.class);SpringRunner extends SpringJUnit4ClassRunner 13 @RunWith(SpringRunner.class) 14 @SpringBootTest 15 public class PropertiesTest { 16 @Resource 17 private WhhProperties whhProperties; 18 19 @Test 20 public void testProperties() throws Exception { 21 System.out.println("title:"+whhProperties.getTitle()); 22 System.out.println("description:"+whhProperties.getDescription()); 23 } 24 25 }
運行結果:
title:whh
description:åäº«ææ¯åçæ´»
------》出現中文亂碼,暫時未解決
11.Spring Data Jpa數據庫連接:
(1)添加依賴:
1 <!--jpa的jar包 ,操作數據庫的,類似hibernate--> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-data-jpa</artifactId> 5 </dependency> 6 <!-- 由於Oracle授權問題,Maven不提供Oracle JDBC driver, 7 為了在Maven項目中應用Oracle JDBC driver,必須手動添加到本地倉庫。 --> 8 <!-- oracle數據庫驅動 --> 9 <dependency> 10 <groupId>com.oracle</groupId> 11 <artifactId>ojdbc6</artifactId> 12 <version>11.2.0.1.0</version> 13 </dependency>
由於Oracle授權問題,Maven不提供Oracle JDBC driver,所以maven的中央倉庫中沒有這個資源(所以會報錯:Missing artifact com.oracle:ojdbc6:jar:11.2.0.1.0,如下圖),
為了在Maven項目中應用Oracle JDBC driver,必須手動添加到本地倉庫

(2)將ojdbc6.jar添加到本地倉庫:
首先,oracle版本11.2.0,需要在--app\product\11.2.0\dbhome_1\jdbc\lib路徑下找到ojdbc6.jar,也可以到官網下載。
然后將
然后將ojdbc6.jar 放在某目錄:然后cmd--命令行:在該目錄下輸入:
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.1.0 -Dpackaging=jar -Dfile=ojdbc6.jar

執行成功。
然后右擊項目-》maven-》update Project-》OK
更新項目后pom.xml就不會報錯了
(3)添加配置文件
新建properties文件:點擊:src/main/resources目錄---》點擊File菜單---》new ---》FIle--》FIle name:datasource.properties---》finish。完成資源文件的創建
(4)備注整理在springboot的application.properties中,配置各種數據庫的方法:
轉載自:http://blog.chinaunix.net/uid-24648266-id-5758602.html
mysql
- spring.jpa.database=MYSQL
- spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mydbname?useSSL=false
- spring.datasource.username=user1
- spring.datasource.password=user1
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.34</version>
- </dependency>
oracle
- spring.jpa.database = oracle
- spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
- spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
- spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:xe
- spring.datasource.username=user1
- spring.datasource.password=user1
- <dependency>
- <groupId>com.oracle</groupId>
- <artifactId>ojdbc7</artifactId>
- <version>12.1.0.2.0</version>
- </dependency>
sqlserver
- spring.jpa.database = sql_server
- spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.SQLServerDialect
- spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
- spring.datasource.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=mydbname
- spring.datasource.username=user1
- spring.datasource.password=user1
- <dependency>
- <groupId>com.microsoft.sqlserver</groupId>
- <artifactId>mssql-jdbc</artifactId>
- <version>6.1.0.jre8</version>
- </dependency>
(5)啟動項目報錯:Cannot determine embedded database driver class for database type NONE

(51)問題分析:
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
這是因為spring boot默認會加載org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration類,DataSourceAutoConfiguration類使用了@Configuration注解向spring注入了dataSource bean。因為工程中沒有關於dataSource相關的配置信息,當spring創建dataSource bean因缺少相關的信息就會報錯。所以阻止spring boot自動注入dataSource bean
因為我僅僅只是使用spring boot來寫一些很簡單的例子來學習它,在Application類上增加@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
代碼如下:
1 package com.yst.helloWorld; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 import org.springframework.boot.autoconfigure.SpringBootApplication; 6 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 7 import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; 8 import org.springframework.context.annotation.ComponentScan; 9 import org.springframework.stereotype.Controller; 10 11 @SpringBootApplication 12 //@Controller 13 //@EnableAutoConfiguration 14 //@ComponentScan("com.yst.helloWOrld.web") 15 @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) 16 public class HelloWorldApplication { 17 18 public static void main(String[] args) { 19 //啟動Spring Boot項目的唯一入口 20 SpringApplication.run(HelloWorldApplication.class, args); 21 } 22 }
但是重新啟動還是報錯:錯誤如下:

原因:@SpringBootApplication = (默認屬性)@Configuration + @EnableAutoConfiguration + @ComponentScan。springboot會自動注入數據源,而你卻沒有配,所以他就拋出該異常。
這說明剛才的@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})並沒有起到不注入數據源的作用,是哪里出錯了嗎?
查資料好像應該是配置這個:@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
代碼如下
1 package com.yst.helloWorld; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 import org.springframework.boot.autoconfigure.SpringBootApplication; 6 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 7 import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; 8 import org.springframework.context.annotation.ComponentScan; 9 import org.springframework.stereotype.Controller; 10 11 @SpringBootApplication 12 //@Controller 13 //@EnableAutoConfiguration 14 //@ComponentScan("com.yst.helloWOrld.web") 15 @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class}) 16 public class HelloWorldApplication { 17 18 public static void main(String[] args) { 19 //啟動Spring Boot項目的唯一入口 20 SpringApplication.run(HelloWorldApplication.class, args); 21 } 22 }
啟動,報錯:
org.apache.catalina.LifecycleException: Failed to start component [Connector[HTTP/1.1-8080]] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.StandardService.addConnector(StandardService.java:225) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.addPreviouslyRemovedConnectors(TomcatEmbeddedServletContainer.java:265) [spring-boot-1.5.16.RELEASE.jar:1.5.16.RELEASE] at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(TomcatEmbeddedServletContainer.java:208) [spring-boot-1.5.16.RELEASE.jar:1.5.16.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:297) [spring-boot-1.5.16.RELEASE.jar:1.5.16.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:145) [spring-boot-1.5.16.RELEASE.jar:1.5.16.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) [spring-context-4.3.19.RELEASE.jar:4.3.19.RELEASE] at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.5.16.RELEASE.jar:1.5.16.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.16.RELEASE.jar:1.5.16.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.16.RELEASE.jar:1.5.16.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.16.RELEASE.jar:1.5.16.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.16.RELEASE.jar:1.5.16.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.16.RELEASE.jar:1.5.16.RELEASE] at com.yst.helloWorld.HelloWorldApplication.main(HelloWorldApplication.java:20) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.16.RELEASE.jar:1.5.16.RELEASE] Caused by: org.apache.catalina.LifecycleException: Protocol handler start failed at org.apache.catalina.connector.Connector.startInternal(Connector.java:1020) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ~[tomcat-embed-core-8.5.34.jar:8.5.34] ... 18 common frames omitted Caused by: java.net.BindException: Address already in use: bind at sun.nio.ch.Net.bind0(Native Method) ~[na:1.8.0_181] at sun.nio.ch.Net.bind(Net.java:433) ~[na:1.8.0_181] at sun.nio.ch.Net.bind(Net.java:425) ~[na:1.8.0_181] at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223) ~[na:1.8.0_181] at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74) ~[na:1.8.0_181] at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:219) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:1151) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:591) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.connector.Connector.startInternal(Connector.java:1018) ~[tomcat-embed-core-8.5.34.jar:8.5.34] ... 19 common frames omitted 2019-02-25 18:38:49.873 INFO 9852 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2019-02-25 18:38:49.973 INFO 9852 --- [ restartedMain] utoConfigurationReportLoggingInitializer : Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 2019-02-25 18:38:50.009 ERROR 9852 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the connector may be misconfigured. Action: Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.
原來是8080端口被占用:
解決步驟:打開cmd命令窗口 輸入指令:netstat -ano 查看所有端口和PID,如下圖所示:
然后找到對應的端口對應的PID 輸入指令: tasklist | findstr "15132" 找到對應的進程;輸入 命令:taskkill /f /t /im javaw.exe 殺掉該進程就可以啦(殺進程也可以使用kill命令:kill xxx,常用::kill -9 pid)

重新啟動,啟動成功:如圖:

