1. 程式人生 > >SpringBoot學習筆記-基礎專案搭建

SpringBoot學習筆記-基礎專案搭建

       因為工作需要,最近研究springBoot框架,從零開始什麼都不懂,雖然只是基礎的專案搭建,但是還是遇到了不少的坑,特此記錄下。

        首先,現在開發工具上安裝一個spring的外掛(懶人專用),這樣可以直接生成springBoot專案,不用一個檔案一個檔案的重新構建。我的開發工具是Eclipse, 步驟 :hellp》Eclipse Marketplace 》popular


然後找見spring Tool是 點選installed然後等一會,等安裝結束後進入 window》preferences檢視是否有spring的外掛,如圖:


看到spring就說明外掛安裝完成,可以進入下一步,構建專案

右鍵new一個新專案,不過我們選擇other然後輸入spring可以發現可以直接生成springBoot專案


選中springBoot 下的spring starter project 點選下一步會出現下圖


說一下比較重要的部分:

    Name是專案名稱

    packging是打包方式:jar/war

    java version是java版本

    package 是構建後的專案路徑

都配置好後點擊下一步:


springBoot的強大這時候就體現出來了,他將大部分我們可能用到的東西都整合進來,可以直接使用,只需要勾選你所需要的東西就行,因為只是一個簡單額demo,所以只勾選幾個可能用到的


然後點選finish生成專案,生成的目錄結構如下


SpringBootDemo1Application是專案入口,開發啟動時需要直接main方法啟動就行

application.properties是springboot的配置檔案,大部分配置都在裡面,字尾可以改成.yml,需要注意的是,不同字尾的配置檔案寫法是不一定的

application.properties

spring.application.name=compute-service
server.port=80
server.tomcat.uri-encoding=GBK
application.yml
spring: 
  datasource:
    url: jdbc:mysql:資料庫url
    password: 資料庫密碼
    username: 資料庫使用者名稱
    driver-class-name: com.mysql.cj.jdbc.Driver
  http:
    encoding:
      charset: UTF-8
      enabled: true
mybatis: 
  config-location: classpath:mybatis-config.xml
server:
  port: 8080  
  sessionTimeout: 30
  contextPath: /StringBoot
然後在同級目錄下新增一個mybatis-config.xml檔案,檔案內容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="cacheEnabled" value="true" />
		<setting name="lazyLoadingEnabled" value="false" />
		<setting name="multipleResultSetsEnabled" value="true" />
		<setting name="useColumnLabel" value="true" />
		<setting name="defaultExecutorType" value="REUSE" />
		<setting name="defaultStatementTimeout" value="25000" />
	</settings>
	<plugins>
		<plugin interceptor="com.github.pagehelper.PageHelper">
			<property name="dialect" value="mysql" />
			<property name="offsetAsPageNum" value="true" />
			<property name="rowBoundsWithCount" value="false" />
			<property name="pageSizeZero" value="false" />
			<property name="reasonable" value="true" />
			<property name="supportMethodsArguments" value="false" />
			<property name="returnPageInfo" value="none" />
		</plugin>
	</plugins>
</configuration>
然後修改pom檔案,新增一些依賴,修改後為:
<?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>com.example</groupId>
    <artifactId>springBootDemo-1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>springBootDemo-1</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <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>

    <build>
        <plugins>
                 <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                
                <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <classesDirectory>target/classes/</classesDirectory>
                    <archive>
                        <manifest>
                            <mainClass>com.example.demo.SpringBootDemoApplication</mainClass>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>.</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <type>jar</type>
                            <includeTypes>jar</includeTypes>
                            <outputDirectory>
                                ${project.build.directory}/lib
                            </outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                        <manifestEntries>
                            <Premain-Class> . </Premain-Class>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
          </plugins>        
    </build>
</project>
然後選中專案,右鍵:maven》update maven project執行結束後,右鍵,run》mavenclean然後在run》maven install 如果專案打包成功則可以繼續執行,如果打包失敗則說明配置有問題請檢查,springBoot專案中自帶了test測試用例,所以需要引入junit的jar,如果不需要,也可以直接刪除測試用例,測試用例地址在src\test下

然後進入到 SpringBootDemo1Application中  main方法啟動,

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

2017-11-13 15:22:31.772  INFO 2384 --- [           main] c.e.demo.SpringBootDemo1Application      : Starting SpringBootDemo1Application on AGOE2345-311800 with PID 2384 (D:\workspaceTest\springBootDemo-1\target\classes started by Administrator in D:\workspaceTest\springBootDemo-1)
2017-11-13 15:22:31.774  INFO 2384 --- [           main] c.e.demo.SpringBootDemo1Application      : No active profile set, falling back to default profiles: default
2017-11-13 15:22:31.816  INFO 2384 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]6ac13091: startup date [Mon Nov 13 15:22:31 CST 2017]; root of context hierarchy
2017-11-13 15:22:32.343  WARN 2384 --- [           main] o.m.s.mapper.ClassPathMapperScanner      : No MyBatis mapper was found in '[com.example.demo]' package. Please check your configuration.
2017-11-13 15:22:33.025  INFO 2384 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-11-13 15:22:33.039  INFO 2384 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-11-13 15:22:33.041  INFO 2384 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-11-13 15:22:33.128  INFO 2384 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/StringBoot]    : Initializing Spring embedded WebApplicationContext
2017-11-13 15:22:33.128  INFO 2384 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1315 ms
2017-11-13 15:22:33.255  INFO 2384 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-11-13 15:22:33.258  INFO 2384 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-11-13 15:22:33.259  INFO 2384 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-11-13 15:22:33.259  INFO 2384 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-11-13 15:22:33.259  INFO 2384 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-11-13 15:22:33.516  INFO 2384 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]6ac13091: startup date [Mon Nov 13 15:22:31 CST 2017]; root of context hierarchy
2017-11-13 15:22:33.567  INFO 2384 --- [           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-11-13 15:22:33.568  INFO 2384 --- [           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-11-13 15:22:33.591  INFO 2384 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 15:22:33.591  INFO 2384 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 15:22:33.619  INFO 2384 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 15:22:34.011  INFO 2384 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-11-13 15:22:34.074  INFO 2384 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-11-13 15:22:34.080  INFO 2384 --- [           main] c.e.demo.SpringBootDemo1Application      : Started SpringBootDemo1Application in 2.588 seconds (JVM running for 2.872)
看到如下則說明啟動成功,可以進入下一步操作

寫個controller頁面

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

@RestController
@RequestMapping("hello")
public class HelloController {

	@RequestMapping("word")
	public String HelloWord() {
		return "Hello Word";
	}

}

輸入連結 http://127.0.0.1:8080/StringBoot/hello/word


訪問成功

你在這裡訪問的專案名和埠號都在application.yml中,

server:
  port: 埠號
  contextPath: 專案名
訪問成功後,最基礎的springBoot的基礎搭建完成

遇到的錯誤解決方法:

一、Maven 工程錯誤Failure to transfer org.codehaus.plexus:plexus-io:pom:1.0,Failure to transfer org.codehaus.plexus:plexus-archiver:jar:2.0.1

解決方法:

        1.先去掉Maven工程的maven特性,選中工程 滑鼠右鍵-->Maven-->Disable Maven Nature. 此步驟後pom.xml錯誤消失

        2.為工程增加Maven特性,選中工程 滑鼠右鍵-->Configure-->Convert to Maven Project.

經過上述步驟,Maven工程就正常了。

二、執行時報錯: Could not open ServletContext resource [/mybatis-config.xml]
mybatis: 
  config-location: classpath:mybatis-config.xml
請注意,如果classpath沒寫就會報這個錯誤
三、訪問專案時如果出現


類似的錯誤,在訪問的controller和方法都沒問題的情況下,請檢查你的專案入口


是否你的專案入口類必須在Controller的上一層,正確的位置路徑如下


專案git地址:[email protected]:xzxWord/SpringBoot.git

相關推薦

SpringBoot學習筆記-基礎專案搭建

       因為工作需要,最近研究springBoot框架,從零開始什麼都不懂,雖然只是基礎的專案搭建,但是還是遇到了不少的坑,特此記錄下。         首先,現在開發工具上安裝一個spring的外掛(懶人專用),這樣可以直接生成springBoot專案,不用一個檔案

SpringBoot 學習筆記(一)——Spring回顧與SpringMVC基礎

Spring Boot學習筆記(一) 一、Spring 回顧 1、宣告Bean 的註解 @Component 元件,沒有明確的角色 @Service 業務邏輯層(service層)使用 @Repository 資料訪問層(dao層)使用 @C

SpringBoot學習筆記02——SpringBoot專案WebSocket推送

SpringBoot中建立WebSocket推送 使用SpringBoot建立WebSocket推送比較簡單,只需要以下三步即可。 1.建立一個配置類 WebSocketConfig package com.adc.da.publish.websocket.config; import

SpringBoot學習筆記01——建立SpringBoot專案HelloWorld

使用IDEA建立SpringBoot專案 HelloWorld 1.File->New->Project 2.選擇Spring Initializr 點選Next。  3.填寫專案Group和Artfact 點選Next。 4.等待ma

SpringBoot基礎專案搭建及各種整合和專案原始碼

SpringBoot基礎專案搭建及各種整合    專案原始碼:連結:https://pan.baidu.com/s/1OExnvhWeW5oQK8BHMAdH3A   提取碼:2pbj  1.1、SpringBoot簡介 1.2、

React學習(一)——基礎專案搭建以及環境配置

大家好,我是凱文,本篇文章將介紹React前端框架的環境配置以及專案搭建方法,其中涉及到了node.js(js執行平臺)、npm(依賴包管理工具)等內容。網上已經有許多類似的教程,這篇文章可以給各位做個參考,同時給我自己當做一個筆記。     React作為時下較為熱門的前

SpringBoot學習筆記(二) SpringBoot專案建立的兩種方式

叄念 springboot 專案建立方式其實有多種,這裡我們主要介紹兩種方式: 當然這裡建議大家用方式一來建立,方式二用於理解 方式

《Gradle構建SpringBoot學習筆記》第二章:建立基於Gradle構建的Spring Boot Web專案

1.生成初始化專案 通過 SpringBoot 官方提供的 Spring Initializr初始化一個Web專案,網址為https://start.spring.io/,瀏覽器開啟該網址顯示如下 選擇構建Gradle Project,語言選擇Java,Spr

SpringBoot 學習筆記(一) 新建SpringBoot專案

環境/版本: 開發工具:Eclipse java 2018-09 SpringBoot: 2.0.0.RELEASE maven: 3.5.3 開始: 建立專案: 訪問Spring Initializr,按圖1.1所示輸入Group,Artifact會自動生成對

springboot學習筆記(一):基礎程式和配置

1 , springboot 介紹(來自百度百科) 簡介 微服務是一個新興的軟體架構,就是把一個大型的單個應用程式和服務拆分為數十個的支援微服務。一個微服務的策略可以讓工作變得更為簡便,它可擴充套件單個元件而不是整個的應用程式堆疊,從而滿足服務等級協議。

React學習-----基礎專案搭建以及環境配置

首先,我們需要安裝node.js,直接搜尋並在官網下載安裝包。     node.js官網:https://nodejs.org/en/ 現在我們成功安裝了node和npm,然後我們來用npm建立新的專案,首先用npm 安裝 create-react-app工具,其可以自動地在本地目錄

springboot學習(個人學習筆記)-4- 搭建ssm框架,完成crud操作

宣告:寫此部落格是為了記錄個人技術學習的全過程,防止後期時間久了會有遺忘。希望同時也能幫到有需要的朋友一、建立springboot專案右鍵New-Spring Starter-Project選擇war包搜尋並新增依賴建立完成二、修改pom.xml,新增對jsp支援的依賴程式碼

1.【springboot學習筆記】-基礎概念

一、為什麼使用springboot? springboot的配置少 專案可以快速搭建 內嵌Servlet容器,降低了對環境的要求,可以使用命令直接執行專案,應用可用jar包執行:java -jar; (以前的打包方式:打包成一個war包放入到tomcat/webapps

Spring學習筆記 使用SpringMVC搭建第一個專案

  近來公司沒什麼新的專案,於是打算抽時間看看java著名的三大框架Struts、Hibernate、Spring;之前看了Struts,從今天起,準備好好審視並學習Spring mvc,學習Spring mvc的第一步,當然是環境的搭建以及一個可以執行的最簡單

Tensorflow學習筆記 (基礎-第一篇)------ 搭建神經網路,總結搭建八股

---- 內容                                                                                                                     1、基本概念 2、神經網

springboot 系列教程一:基礎專案搭建

使用 spring boot 有什麼好處 其實就是簡單、快速、方便!平時如果我們需要搭建一個 spring web 專案

Python學習筆記-基礎Day01

虛擬機 python 處理器 Python與其他語言的對比:C 和 Python、Java、C#對比C語言:代碼編譯得到機器碼,機器碼在處理器上直接執行。其他語言:代碼編譯得到字節碼,虛擬機執行字節碼並轉換成機器碼然後在處理器上執行Python之類的高級語言相對C語言開發效率較高,不需要開發者考慮

Redux學習筆記-基礎知識

事件處理 學習筆記 情況 分發 .org 新的 分數 class 特點 p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px "Helvetica Neue"; color: #404040 } p.p2 { margin

HTML學習筆記基礎表格 第二節 (原創)

utf 空心圓 無序列表 har ble 學習 oot order 有序 <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title

HTML學習筆記 基礎標簽及css引用案例 第一節 (原創)參考使用表

set utf har del 文件 定義 .com eight head <!DOCTYPE html><!--頭文件 不是標簽 也沒有結束,這是聲明該文件為HTML5--><html lang="en"><!--表示網頁文字以什