第一章 Hello, Spring Boot

本章是《 Spring Boot 快速入门 》系列教程的第一章,若要查看本系列的全部章节,请点击 这里

目录

  • 简介
  • 源码下载
  • 软件版本
  • 创建项目
  • 编写 HelloService 类
  • 编写 SpringBoot 主程序
  • 运行效果
  • 总结说明

简介

本章我将用Spring Boot开发一个类似于"Hello, World"的程序,我们将它称之为“Hello, Spring Boot”。 通过这个小小的Demo程序,让对Spring Boot完全不了解的Java开发者可以快速上手,使用Spring Boot进行开发。

源码下载

本章的示例代码放在“码云”上,大家可以免费下载或浏览: https://git.oschina.net/terran4j/springboot/tree/master/springboot-hello

软件版本

相关软件使用的版本:

  • Java:  1.8
  • Maven:  3.3.9

程序在以上版本均调试过,可以正常运行,其它版本仅作参考。

创建项目

我们用Eclipse(其它IDE类似)创建一个Maven项目,pom.xml文件的内容如下:

<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 定义了很多启动器,下面简单介绍下上面出现过的两个启动器:

  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包含了以下信息:

  • 使用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 进行自动装配,准确来说,它按以下规则进行自动装配: 1、根据类型来找匹配的Bean,如上面就是找类型为 HelloService 类或子类的 Bean ,如果存在并且唯一则OK。 2、如果不唯一,就根据属性名在结果集中找名称相同的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及微服务-公众号二维码

猜你喜欢

转载自my.oschina.net/u/3017144/blog/1499211