第一章 Hello, Spring Boot

本章是《 Spring Boot 快速入門 》系列教程的第一章,若要查看本系列的所有章節,請點擊 這裏 java

目錄

  • 簡介
  • 源碼下載
  • 軟件版本
  • 建立項目
  • 編寫 HelloService 類
  • 編寫 SpringBoot 主程序
  • 運行效果
  • 總結說明

簡介

本章我將用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

  • Java:  1.8
  • Maven:  3.3.9

程序在以上版本均調試過,能夠正常運行,其它版本僅做參考。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

  1. spring-boot-starter-parent: 定義一個父pom,使用時須要你項目的pom繼承它,就像這樣:
<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
	</parent>

spring-boot-starter-parent包含了如下信息:springboot

  • 使用java6編譯級別
  • 使用UTF-8編碼
  • 提供了通用的測試框架 (JUnit, Hamcrest, Mockito).
  • 定義了大量開源jar包的依賴管理(實際上是它的父pom: spring-boot-dependencies定義的),從而引用這些開源jar包是不用指定版本號,這樣會避免引入不一樣開源項目所形成的jar包版本衝突,由於Spring Boot都幫你解決好了這些兼容性問題。
  • 定義了不少插件的依賴管理,如: exec plugin, surefire, Git commit ID, shade等。
  1. spring-boot-starter-web: 提供了Web開發時所須要的模塊,包含如下信息:
  • 默認嵌入 tomcat 做爲Web容器。
  • 提供了Spring MVC框架
  • 提供了其它Web項目經常使用的模塊,如:spring-web, jackson-databind等。

建立完這個Maven項目以後的目錄結構以下:微信

image.png

編寫 HelloService 類

接下來,咱們編寫一個很是簡單的類——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 的註解有:

  • @Component: 聲明一個Bean,但這個 Bean 沒有明確的角色。
  • @Service: 聲明一個Bean,在業務邏輯層(Service層)使用。
  • @Respository: 聲明一個Bean,在數據訪問層(DAO層)使用。
  • @Controller: 聲明一個Bean,在展示層(MVC / Spring MVC)使用。 後面三個註解(@Service、@Respository、@Controller)都是繼承了 @Component 註解,其實本質上是和 @Component 是同樣的,好比 @Service 的代碼以下:
@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後續版本中,有可能會給它們賦予不一樣的功能。

編寫 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及微服務 的微信公衆號,感興趣的同窗請掃描下面的二維碼關注下吧,關注後就能夠收到咱們按期分享的技術乾貨哦! SpringBoot及微服務-公衆號二維碼

相關文章
相關標籤/搜索