Springboot的第一個程序

一、什麼是Springboot

隨著動態語言的流行(Ruby、Groovy、Scala、Node.js),Java的開發顯得格外的笨重:繁多的配置、低下的開發效率、複雜的部署流程以及第三方技術集成難度大。在上述環境下,Springboot應運而生。它使用"習慣優於配置"(項目中存在大量的配置,此外還內置一個習慣性的配置,讓你無須手動進行配置)的理念讓你的項目快速運行起來。使用springboot很容易創建一個獨立運行(運行jar,內嵌servlet容器)、準生產級別的基於Spring框架的項目,使用springboot你可以不用或者只需要很少的Spring配置。

二、Springbot的優缺點

優點:

1.快速構建項目;
2.對主流開發框架的無配置集成;
3.項目可獨立運行,無須外部依賴servlet容器;
4.提供運行時的應用監控;
5.極大地提高了開發、部署效率;
6.與雲計算的天然集成。

缺點:

1.書籍文檔較少且不夠深入;
2.如果你不認同Spring框架,這也許是它的缺點,但建議你一定要使用Spring框架。

三、Springboot入門程序

(1)設置spring boot的parent


org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE

說明:Spring boot的項目必須要將parent設置為spring boot的parent,該parent包含了大量默認的配置,大大簡化了我們的開發。

(2)導入spring boot的web支持


org.springframework.boot
spring-boot-starter-web

(3)添加Spring boot的插件


org.springframework.boot
spring-boot-maven-plugin

即pom.xml:


4.0.0

org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE

com.hcx.springboot
hcx-springboot
0.0.1-SNAPSHOT
war


org.springframework
spring-webmvc
4.3.7.RELEASE



com.jolbox
bonecp-spring
0.8.0.RELEASE



org.springframework.boot
spring-boot-starter-web




${project.artifactId}



org.apache.maven.plugins
maven-resources-plugin

UTF-8




org.apache.maven.plugins

maven-compiler-plugin

1.7
1.7
UTF-8



org.springframework.boot
spring-boot-maven-plugin







org.apache.tomcat.maven
tomcat7-maven-plugin
2.2





(4)編寫第一個Spring Boot的應用

package com.hcx.springboot.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@SpringBootApplication //聲明這是一個springboot的應用
@Configuration //聲明該類為一個配置類
public class HelloApplication {
//springboot的項目命名中,一般都有一個xxxApplication類,該類作為springboot項目的入口類

@RequestMapping("hello")
@ResponseBody
public String hello(){
return "hello world";
}

public static void main(String[] args) {
/**
* 第一個參數:要運行的應用(該應用一定要包含@SpringBootApplication註解)
* 第二個參數:直接用args,也可以指定內置參數
*/
SpringApplication.run(HelloApplication.class, args);
}
}

代碼說明:

1、@SpringBootApplication:Spring Boot項目的核心註解,主要目的是開啟自動配置;
2、@Configuration:這是一個配置Spring的配置類;
3、@Controller:標明這是一個SpringMVC的Controller控制器;
4、main方法:在main方法中啟動一個應用,即:這個應用的入口;

(5)啟動應用

在Spring Boot項目中,啟動的方式有兩種,一種是直接run Java Application另外一種是通過Spring Boot的Maven插件運行。

第一種:

Springboot的第一個程序

第一種啟動方式.png

第二種:

Springboot的第一個程序

第二種啟動方式.png

啟動效果:

Springboot的第一個程序

啟動效果.png

看到如下信息就說明啟動成功了:

INFO 6188 --- [ main] c.i.springboot.demo.HelloApplication : Started HelloApplication in 3.281 seconds (JVM running for 3.601)

(6)測試

打開瀏覽器,輸入地址:127.0.0.1:8080/hello

Springboot的第一個程序

啟動.png

Springboot的第一個程序


分享到:


相關文章: