本章是《 Spring Boot 快速入門 》系列教程的第一章,若要查看本系列的所有章節,請點擊 這裏 。java
本章我將用Spring Boot開發一個相似於"Hello, World"的程序,咱們將它稱之爲「Hello, Spring Boot」。 經過這個小小的Demo程序,讓對Spring Boot徹底不瞭解的Java開發者能夠快速上手,使用Spring Boot進行開發。git
本章的示例代碼放在「碼雲」上,你們能夠免費下載或瀏覽: https://git.oschina.net/terran4j/springboot/tree/master/springboot-hello程序員
相關軟件使用的版本:web
程序在以上版本均調試過,能夠正常運行,其它版本僅做參考。spring
咱們用Eclipse(其它IDE相似)建立一個Maven項目,pom.xml文件的內容以下:apache
<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>terran4j</groupId> <artifactId>springboot-hello</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-hello</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
spring-boot-starter-** 的項目稱之爲 Spring Boot 啓動器(Starter), 是 Spring Boot 提供的四大神器之一。它們可以很是方便的進行包管理, 很大程度上減小了jar hell或者dependency hell,你只須要在pom.xml中引入它們便可,而不須要不少繁瑣的jar包依賴的配置,從而最大程度的避免了jar版本衝突的問題。編程
Spring Boot 定義了不少啓動器,下面簡單介紹下上面出現過的兩個啓動器:tomcat
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent>
spring-boot-starter-parent包含了如下信息:springboot
建立完這個Maven項目以後的目錄結構以下:微信
接下來,咱們編寫一個很是簡單的類——HelloService,代碼以下:
package com.terran4j.springboot.hello; import org.springframework.stereotype.Component; @Component public class HelloService { public String hello(String name) { return "Hello, " + name + "!"; } }
這個類很是簡單,關鍵是 HelloService 類上的註解: @Component,它聲明瞭一個Spring Bean,Spring容器掃描到有這個註解的類,就會注入到Spring容器中。
Spring Boot 推薦使用註解的方式注入一個Bean到Spring容器中,而不是像之前的Spring程序同樣要寫大量的XML配置,Spring Boot僅須要用Java代碼或註解就能夠完成Spring Bean的配置。
聲明 Bean 的註解有:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Service { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any */ String value() default ""; }
能夠看到 @Service 上有一個 @Component 註解。 目前它們的做用是同樣的,僅僅讓代碼更易於理解,不過Spring Boot後續版本中,有可能會給它們賦予不一樣的功能。
下面咱們編寫一個 main 程序,來調用 HelloService ,代碼以下:
package com.terran4j.springboot.hello; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HelloApp implements ApplicationRunner { @Autowired private HelloService helloService; @Override public void run(ApplicationArguments args) throws Exception { String msg = helloService.hello("Spring Boot"); System.out.println(msg); } public static void main(String[] args) { SpringApplication.run(HelloApp.class, args); } }
咱們先看這段代碼,它聲明瞭一個 HelloService 屬性 helloService :
@Autowired private HelloService helloService;
@Autowired 的做用是讓 helloService 引用 Spring 容器中的 HelloService Bean 對象。 Spring容器很是智能,它會查找與當前屬性最「匹配」的 Bean 進行自動裝配,準確來講,它按如下規則進行自動裝配: 一、根據類型來找匹配的Bean,如上面就是找類型爲 HelloService 類或子類的 Bean ,若是存在而且惟一則OK。 二、若是不惟一,就根據屬性名在結果集中找名稱相同的Bean,如上面就是找名稱爲 helloService 的 Bean 。由於bean的name有惟一性,因此,到這裏應該能肯定是否存在知足要求的bean了。
自動裝配 Bean 了以後,就可使用這個Bean了,以下代碼所示:
@Override public void run(ApplicationArguments args) throws Exception { String msg = helloService.hello("Spring Boot"); System.out.println(msg); }
因爲本類HelloApp implements ApplicationRunner 並覆蓋了 run 方法,Spring 應用程序會在啓動時調用 run 方法。
最後咱們在 main 函數中啓動Spring Boot 應用程序,如:
public static void main(String[] args) { SpringApplication.run(HelloApp.class, args); }
注意,SpringApplication.run方法的第一個參數是啓動類的類對象,這個類在聲明時必須加上 @SpringBootApplication 註解才表示它是一個啓動類。 @SpringBootApplication 註解是三個註解 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan 的合集,它的定義以下:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { // 此處省略,重點看類上面的三個註解。 }
它會在當前啓動類所在的包及其子包下掃描,凡是聲明瞭 @Component 註釋或繼承了 @Component 的註釋(如@Service、@Respository、@Controller或你本身定義的)的類,都會被注入到Spring容器中。
最後咱們運行下 HelloApp 程序,控制檯輸出以下:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.2.RELEASE) // 中間省略一大段日誌信息...... 2017-07-31 08:57:33.330 INFO 53416 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-07-31 08:57:33.421 INFO 53416 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) Hello, Spring Boot! 2017-07-31 08:57:33.428 INFO 53416 --- [ main] com.terran4j.springboot.hello.HelloApp : Started HelloApp in 4.889 seconds (JVM running for 5.356)
倒數第2行出現了「Hello, Spring Boot!」,運行結果符合預期。 倒數第3行出現了「Tomcat started on port(s): 8080 (http)」,表示使用內嵌的Tomcat啓動了Http Web服務,但本章咱們尚未涉及到Web方面的開發,下一章咱們會介紹Web服務方面的開發。
文章主要是帶新手入門,最短期體驗到 Spring Boot 的開發運行流程,從下一章《Spring Boot MVC》開始,咱們帶你們進入實戰技巧的學習,讓你們掌握 Spring Boot 的基本開發技能。
點擊 這裏 能夠查看本系列的所有章節。 (本系列的目標是幫助有 Java 開發經驗的程序員們快速掌握使用 Spring Boot 開發的基本技巧,感覺到 Spring Boot 的極簡開發風格及超爽編程體驗。)
另外,咱們有一個名爲 SpringBoot及微服務 的微信公衆號,感興趣的同窗請掃描下面的二維碼關注下吧,關注後就能夠收到咱們按期分享的技術乾貨哦!