想想之前搭建一個WEB項目,不管項目的功能簡單或復雜,都需要哪些步驟:
對于很多新手來說,很多配置還有很多問題,并不能一次成功
那 springboot 有什么優點呢?
核心理念:開箱即用,快速啟動
Springboot教程、它使用“約定優于配置”(項目中存在大量的配置,此外還內置了一個習慣性的配置,讓你無需手動進行配置)的理念讓你的項目快速運行起來。使用Spring Boot很容易創建一個獨立運行(運行jar,內嵌Servlet容器)、準生產級別的基于Spring框架的項目,使用Spring Boot你可以不用或者只需要很少的Spring配置。
約定優于配置
也稱作按約定編程,是一種軟件設計范式,旨在減少軟件開發人員需做決定的數量,獲得簡單的好處,而又不失靈活性。本質是說,開發人員僅需規定應用中不符約定的部分。
從本質上來說,Spring Boot就是Spring,它只是做了一些對Spring Bean的默認配置。有了SpringBoot只需要幾個配置就可以搭建一個web項目!使用 Spring Boot 到底有多爽,用下面這幅圖來表達
這里介紹使用 IDEA 來創建項目
myproject
+-src+- main+- java+- com.example.myproject+- comm+- model+- repository+- service+- web+- Application.java+- resources+- static+- templates+- application.properties+- test
+-pom.xml
Application.java
建議放到根目錄下面,是項目的啟動類,Spring Boot 項目只能有一個 main()
方法;comm
目錄建議放置公共的類,如全局的配置文件、工具類等;model
目錄主要用于實體(Entity)與數據訪問層(Repository);repository
層主要是數據庫訪問層代碼;service
層主要是業務類代碼;web
層負責頁面訪問控制,即controller
或 handler
。static
目錄存放 web 訪問的靜態資源,如 js、css、圖片;templates
目錄存放頁面模板;application.properties
存放項目的配置信息。pom.xml
引入依賴unable to start servletwebserver。首先,以 parent 引入 SpringBoot
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.7.RELEASE</version><relativePath/> <!-- lookup parent from repository -->
</parent>
然后,引入 web 依賴
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
</dependencies>
默認讀取 classpath 下的 application.properties
或 application.yml
,推薦使用 yml 文件格式。
建議配置多個不同環境的文件,只需兩步:
dev
表示開發環境,prod
表示生產環境,命名規則根據個人或公司而定;spring:profiles:active: dev
application-dev.yml
,該文件內配置一些不同環境的配置。HelloApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class HelloApplication {public static void main(String[] args) {SpringApplication.run(CsttApplication.class, args);}
}
@RestController
public class HelloWorldController {@RequestMapping("/hello")public String index() {return "Hello World";}
}
@RestController
的意思就是 Controller 里面的方法都以 json 格式輸出,不用再寫什么 jackjson 配置的了!啟動主程序,打開瀏覽器訪問 http://localhost:8080/hello
,就可以看到效果了。
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态