本章是《 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及微服务 的微信公众号,感兴趣的同窗请扫描下面的二维码关注下吧,关注后就能够收到咱们按期分享的技术干货哦!