spring-boo hello world程序
作為一個程序猿,使用了spring好多年,現在有了spring-boot,也想嘗嘗鮮。
初聽spring-boot,覺得很神秘,實際上就是集合了很多組件,再加上一些boot開發的啟動和粘合程序。 個人見解,不一定對。
構建過程
使用 Spring Initializr ,我使用idea構建的,在新項目裏面有一個Spring Initializr 選項,如圖:
設置項目屬性,如圖:
選擇spring-boot組件:
設置項目名:
完成就可以了
第一個程序
新建Java程序
package com.sun.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.*; @RestController @EnableAutoConfiguration public class Application { @RequestMapping("/helloworld") public String home() { return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
查看build.gradle文件
buildscript { ext { springBootVersion = ‘1.5.4.RELEASE‘ } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: ‘java‘ apply plugin: ‘eclipse‘ apply plugin: ‘org.springframework.boot‘ version = ‘0.0.1-SNAPSHOT‘ sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(‘org.springframework.boot:spring-boot-starter-web‘) runtime(‘mysql:mysql-connector-java‘) testCompile(‘org.springframework.boot:spring-boot-starter-test‘) }
程序結構如下:
運行
運行Application,輸出如下:
. ____ _ __ _ _ /\\ / ___‘_ __ _ _(_)_ __ __ _ \ \ \ ( ( )\___ | ‘_ | ‘_| | ‘_ \/ _` | \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ‘ |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.4.RELEASE) 2017-07-19 08:22:36.552 INFO 8372 --- [ main] com.sun.boot.Application : Starting Application on sunzuoquan-Inspiron-7466 with PID 8372 (/home/sunzuoquan/IdeaProjects/demo/build/classes/java/main started by sunzuoquan in /home/sunzuoquan/IdeaProjects/demo) 2017-07-19 08:22:36.583 INFO 8372 --- [ main] com.sun.boot.Application : No active profile set, falling back to default profiles: default 2017-07-19 08:22:37.041 INFO 8372 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbedde[email protected]
從日誌可以看出,Tomcat started on port(s): 8080,spring-boot內部啟動了tomcat,監聽8080端口。
打開瀏覽器,訪問:http://localhost:8080/helloworld
瀏覽器輸出如下:
spring-boo hello world程序