Spring Boot 2.0 常見問題總結(一)

  • SpringBoot2.x 依賴環境和版本新特性說明

    依賴版本 jdk8 以上, Springboot2.x 用 JDK8 , 因爲底層是 Spring framework5 。

  • jar 包方式運行 SpringBoot 項目時問題

    打包成jar包,需要增加maven依賴。

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

    如果沒加相關依賴,執行 maven 打包,運行後會報錯: no main manifest attribute, in XXX.jar。

    原因解釋:

    將 jar 文件文件後綴改爲 zip 解壓後得到目錄如下:

    		example.jar
    			 |
    			 +-META-INF
    			 |  +-MANIFEST.MF
    			 +-org
    			 |  +-springframework
    			 |     +-boot
    			 |        +-loader
    			 |           +-<spring boot loader classes>
    			 +-BOOT-INF
    				+-classes
    				|  +-mycompany
    				|     +-project
    				|        +-YourClasses.class
    				+-lib
    				   +-dependency1.jar
    				   +-dependency2.jar
    

    當沒有引用 maven 插件的時候,就沒有生成的 MANIFEST.MF 文件,而在 MANIFEST.MF 中有 Main-Class: org.springframework.boot.loader.JarLauncher,這會啓動類加載器,類加載器會加載應用的主要函數,即執行 Start-Class: com.rookie.BaseProjectApplication,這就是程序入口。運行後會報錯:no main manifest attribute, in XXX.jar,就是找不到 MANIFEST.MF 的
    Start-Class: xx.xx.xxApplication。入口函數都找不到,你說如何啓動加載呢?肯定會加載失敗的。

  • @RestController 和 @RequestMapping 註解不生效

    引入 Web 模塊,需在 pom.xml 添加 spring-boot-starter-web 模塊

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
  • SpringBoot 啓動失敗信息如下:
    ***************************
    APPLICATION FAILED TO START
    ***************************
    Description:
    Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
    Reason: Failed to determine a suitable driver class
    Action:
    Consider the following:
    	If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    	If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
    Process finished with exit code 1
    

    原因是:創建 Spring Boot 項目時,在選擇組件時添加了 mysql、mybatis 組件,添加了數據庫組件,所以 autoconfig 會去讀取數據源配置,而新建的項目還沒有配置數據源,所以會導致異常出現。

    解決方案:

    ①:需要在啓動類的 @EnableAutoConfiguration 或 @SpringBootApplication 中添加

    exclude = {DataSourceAutoConfiguration.class},排除此類的autoconfig。

    ②:添加數據庫配置信息

    spring.datasource.jdbc-url=jdbc:mysql://localhost:3316/test1
    spring.datasource.username=root
    spring.datasource.password=root
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    
  • service 注入失敗、@Autowired 注入失敗 參考以下鏈接

    https://my.oschina.net/hxflar1314520/blog/1800035

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章