首页 > 编程技术 > java

Spring Boot应用开发初探与实例讲解

发布时间:2021-7-29 15:00

Spring Boot是由Pivotal团队提供的全新Spring开发框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。

从它的名字可以看出,Spring Boot 的作用在于创建和启动新的基于 Spring 框架的项目。

它的目的是帮助开发人员很容易的创建出独立运行和产品级别的基于 Spring 框架的应用。

它包含的特性如下:

在这节课中,我们将对Spring Boot的方方面面进行初步的探索,看看Spring Boot究竟能为我们提供怎样的开发能力。

环境准备

使用Gradle作为项目构建工具

首先创建一个项目目录,在目录中创建一个Gradle项目描述文件build.gradle:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE"
        classpath "com.github.adrianbk:gradle-jvmsrc-plugin:0.6.1"
    }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'com.github.adrianbk.jvmsrc'
jvmsrc {
    packageName "tmy"
}
jar {
    baseName = 'spring-boot-guides'
    version =  '1.0.0'
}
repositories {
    jcenter()
}
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
}
task wrapper(type: Wrapper) {
    gradleVersion = '2.4'
}

在这个文件中,使用到了Spring Boot Gradle插件来帮助我们简化一些配置工作:

另外由于Gradle的默认特性——例如源代码放在src/main/java文件夹下,我们引入Gradle JVM Src插件,通过配置:

apply plugin: 'com.github.adrianbk.jvmsrc'
jvmsrc {
    packageName "tmy"
}

并运行gradle createJvmSrcDirs,src/main/java/tmy等目录就被创建出来,省去我们手动创建的麻烦。

Spring Boot能做什么

Spring Boot本身并没有在Spring框架的基础上扩展新功能,它仅仅是提供了一种更加快速构建Spring应用的方式。Spring Boot会在根据类路径上的依赖(也就是Maven或Gradle中定义的依赖)来自动完成配置。例如:

提示

Spring Boot不会生成或者修改你的源代码,它仅仅是在应用启动时根据类路径以及应用配置动态的改变Spring应用上下文的配置

简单的Web应用

现在我们创建一个最简单的Web应用:

src/main/java/tmy/Application.java

package tmy;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@SpringBootApplication
public class Application {
    @RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        System.out.println("Let's inspect the beans provided by Spring Boot:");
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }
}

@SpringBootApplication是Spring Boot提供的注解,他相当于加上如下注解:

运行Web应用

完成上述配置后,运行应用有两种方法:

在控制台的输出中会发现如下信息:

Let's inspect the beans provided by Spring Boot:
application
beanNameHandlerMapping
defaultServletHandlerMapping
dispatcherServlet
embeddedServletContainerCustomizerBeanPostProcessor
handlerExceptionResolver
helloController
httpRequestHandlerAdapter
messageSource
mvcContentNegotiationManager
mvcConversionService
mvcValidator
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.context.embedded.properties.ServerProperties
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
propertySourcesBinder
propertySourcesPlaceholderConfigurer
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
simpleControllerHandlerAdapter
tomcatEmbeddedServletContainerFactory
viewControllerHandlerMapping

这就是Spring应用上下文中的所有Bean信息,其中有Spring MVC中需要用到的dispatcherServlet, mvcConversionService, mvcValidator等等悉数在列,而我们并没有进行任何的配置,这也就是Spring Boot完成的工作。

访问浏览器或者使用curl:

$ curl localhost:8080
Greetings from Spring Boot!

添加生产环境特性

虽然没有将应用打成WAR包并放入应用服务器中,但Spring Boot本身是可以应用于生成环境的。为了能够获取生产环境的应用信息,Spring Boot提供了开箱即用的模块Actuator:

compile("org.springframework.boot:spring-boot-starter-actuator")

在添加完这个依赖后并启动应用,会看到多了一些URL Mapping信息:

2015-07-24 12:05:33.440  ... : Mapped "{[/info],methods=[GET],params=[],headers=[],consum...
2015-07-24 12:05:33.441  ... : Mapped "{[/autoconfig],methods=[GET],params=[],headers=[],...
2015-07-24 12:05:33.441  ... : Mapped "{[/mappings],methods=[GET],params=[],headers=[],co...
2015-07-24 12:05:33.442  ... : Mapped "{[/trace],methods=[GET],params=[],headers=[],consu...
2015-07-24 12:05:33.442  ... : Mapped "{[/env/{name:.*}],methods=[GET],params=[],headers=...
2015-07-24 12:05:33.442  ... : Mapped "{[/env],methods=[GET],params=[],headers=[],consume...
2015-07-24 12:05:33.443  ... : Mapped "{[/configprops],methods=[GET],params=[],headers=[]...
2015-07-24 12:05:33.443  ... : Mapped "{[/metrics/{name:.*}],methods=[GET],params=[],head...
2015-07-24 12:05:33.443  ... : Mapped "{[/metrics],methods=[GET],params=[],headers=[],con...
2015-07-24 12:05:33.444  ... : Mapped "{[/health],methods=[GET],params=[],headers=[],cons...
2015-07-24 12:05:33.444  ... : Mapped "{[/dump],methods=[GET],params=[],headers=[],consum...
2015-07-24 12:05:33.445  ... : Mapped "{[/beans],methods=[GET],params=[],headers=[],consu...

通过这些URL我们可以获知Spring应用的运行时信息,例如:

$ curl localhost:8080/health
{"status":"UP"}
Spring Boot Starters

为了能够快速开发各类型的应用以及支持种类繁多的第三方库,Spring Boot提供了大量的starter依赖,引入这些依赖后应用即拥有开箱即用的配置,举例:

compile("org.springframework.boot:spring-boot-starter-thymeleaf")

那么只需要将模板文件放入src/main/resources/templates目录下,即可以正常的编写Spring MVC的Web页面了。

总结

Spring 框架作为目前非常流行的一个 Java 应用开发框架,它所包含的内容是非常繁多的。

Spring 框架包含几十个不同的子项目,涵盖应用开发的不同方面。要在这些子项目之间进行选择,并快速搭建一个可以运行的应用是比较困难的事情。Spring Boot 的目的在于快速创建可以独立运行的 Spring 应用。

通过 Spring Boot 可以根据相应的模板快速创建应用并运行。Spring Boot 可以自动配置 Spring 的各种组件,并不依赖代码生成和 XML 配置文件。Spring Boot 可以大大提升使用 Spring 框架时的开发效率。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

标签:[!--infotagslink--]

您可能感兴趣的文章: