SpringBoot2.0 (三)——特性

1. SpringApplication

SpringApplication 提供了一种很方便的方法去引导Spring Application 启动,那就是 main () 方法。在很多情况下,你仅仅需要委托给静态的SpringApplication.run ( ) 方法。

public static void main(String[] args) {
    SpringApplication.run(MySpringConfiguration.class, args);
}
  1. 启动失败
  2. 配置Banner
  3. 配置SpringApplication
    如果默认的SpringApplication配置不适合你的口味,你可以创建一个本地的实例代替它。例如,关闭Banner 你可以这样写。
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
          app.setBannerMode(Banner.Mode.OFF);
          app.run(args);

当然你可以在applicatio.properties 进行配置。

  1. Fluent builder API
    如果你需要构建SpringApplication的层次结构(多个上下文父子关系),或者假如你仅仅是更喜欢用一下“Fluent” builder API,你可以使用 SpringApplicationBuilder。它允许你把多个方法调用链放在一起,包括父/子的方法,让你创建一个层次结构。
    例如:
new SpringApplicationBuilder()
        .sources(Parent.class)
        .child(Application.class)
        .bannerMode(Banner.Mode.OFF)
        .run(args);
  1. Application events 和 listeners
  2. Web environment
  3. Accessing Application argument(访问应用的参数)
  4. 使用ApplicationRunner 和 CommandLIneRunner
    如果你需要在SpringApplication刚启动之后运行一些特殊的代码,你可以继承ApplicationRunner或者CommandLineRunner 接口。这两个接口用同一个方式提供一个在SpringApplication.run(...)完成被调用的run方法。
import org.springframework.boot.*
import org.springframework.stereotype.*
@Component
public class MyBean implements CommandLineRunner {
    public void run(String... args) {
        // Do something...
    }
}
  1. Application exit(退出)
    每一个SpringApplication 都会注册一个shutdown钩子与JVM以确保ApplicationContext关闭可以优雅的退出。Spring所有标准的生命周期回调(例如DisposableBeans接口,或者@PreDestroy注解)可以被使用。
    另外,beans 可能实现org.springframework.boot.ExitCodeGenerator 接口,假如他们希望在应用结束的时候返回一个特殊的退出码。

  2. Admin feature

2. 外部化配置

Spring Boot 允许你去扩展你的配置,所以你可以用同样的Application 代码在不同的环境中工作。你可以使用properties文件、YAML文件,环境变量和命令行参数。属性值可以使用@Value 注解 直接注入到你的Beans中。通过Spring的抽象环境访问或者通过@ConfigurationProperties绑定到结构化对象中。SpringBoot 使用特别的PropertySource 以便允许合理的覆盖值。属性应该按照以下的顺序。(顺序省略,请查看文档。)

  1. 配置随机值
    RandomValuePropertySource 对于注入随机值是很有用处的。他能产出Integers、longs、uuids、strings 等等。
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
  1. 通过命令行访问属性

  2. Application property 文件
    SpringApplication 会从application.properties 文件中加载属性文件并把他们添加到Spring Environment中。 优先级是:

    1. A /config 当前的目录的子目录
    2. 当前目录
    3. A classpath /config package
    4. The classpath root
  3. 类型安全的配置属性
    使用@Value("${property}") 注解去注入配置属性有时会很麻烦,特别是如果你使用多个属性或者数据本质上是分层的。SpringBoot 提供另一种使用属性的方法。允许强类型的bean配置管理和验证你的应用程序。

package com.example;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("foo")
public class FooProperties {

    private boolean enabled;

    private InetAddress remoteAddress;

    private final Security security = new Security();

    public boolean isEnabled() { ... }

    public void setEnabled(boolean enabled) { ... }

    public InetAddress getRemoteAddress() { ... }

    public void setRemoteAddress(InetAddress remoteAddress) { ... }

    public Security getSecurity() { ... }

    public static class Security {

        private String username;

        private String password;

        private List<String> roles = new ArrayList<>(Collections.singleton("USER"));

        public String getUsername() { ... }

        public void setUsername(String username) { ... }

        public String getPassword() { ... }

        public void setPassword(String password) { ... }

        public List<String> getRoles() { ... }

        public void setRoles(List<String> roles) { ... }

    }
}

你需要将属性类用@EnableConfigurationProperties 注解去注册

@Configuration
@EnableConfigurationProperties(FooProperties.class)
        public class MyConfiguration {
}

尽管上面的配置会创建一个常规的bean,但是我们建议@ConfigurationProperties 只处理环境,而不是从上下文注入到其他的bean。已经说过,@EnableConfigurationProperties注释会自动应用到你的项目,以便任何现有的bean 注释@ConfigurationProperties配置环境。

3. 配置文件

Spring 配置提供了一种方式来隔离部分配置,使其只能在特定的环境中生效。@Component 和 @Configuration 在加载时候可以用@Profile 限制。

@Configuration
@Profile("production")
public class ProductionConfiguration {
    // TODO
}

Spring通常方法是使用spring.profile.active 环境属性去指定哪一个配置被激活。你可以用任何一种常用的方式去指定属性,例如:

spring.profiles.active = dev, hsqldb

或者通过命令行的方式进行指定。

4. 日志

5. 开发 web 应用

SpringBoot 也很适合web的开发。可以很容易的创建一个Tomcat、Jetty、Underow 服务。大部分的web应用使用spring-boot-starter-web 模块开始并快速运行。

  1. Spring Web MVC 框架
    Spring MVC 框架是一个包含“ model view controller ”的web框架。SpringMVC 让我们创建特殊的@Controller 或者是 @RestController beans 去处理HTTP请求。使用@RequestMapping注解去匹配HTTP请求。
@RestController
@RequestMapping(value="/users")
public class MyRestController {
    @RequestMapping(value="/{user}", method=RequestMethod.GET)
    public User getUser(@PathVariable Long user) {
        // ...
    }
    @RequestMapping(value="/{user}/customers", method=RequestMethod.GET)
    List<Customer> getUserCustomers(@PathVariable Long user) {
        // ...
    }
    @RequestMapping(value="/{user}", method=RequestMethod.DELETE)
    public User deleteUser(@PathVariable Long user) {
        // ...
    }
}

Spring MVC 自动配置

  1. 包括 ContentNegotiatingViewResolver 和BeanNameViewResolver beans。
  2. 支持服务静态资源,包括WebJars 的支持
  3. 自动注册Converter、GenericConverter、Formatter beans。
  4. 支持HttpMessageConverters
  5. 自动注册MessageCodesResolver
  6. 静态的index.html
  7. 支持自定义图标
  8. 自动使用ConfigurableWebBindingInitializer bean。

HttpMessageConverters(Http信息转换器)

Spring MVC 使用HttpMessageConverter接口去转换HTTP请求和响应。开箱即用,例如对象可以自动转换成JSON或XML。字符编码默认是UTF-8。如果你需要添加或者定制转换器,看下面例子:

import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;

@Configuration
public class MyConfiguration {

    @Bean
    public HttpMessageConverters customConverters() {
        HttpMessageConverter<?> additional = ...
        HttpMessageConverter<?> another = ...
        return new HttpMessageConverters(additional, another);
    }

}

定制JSON序列化和反序列化

如果你使用Jackson去序列化和反序列化JSON数据,你可能想写你自己的序列化和反序列化的类。SpringBoot 提供了@JsonComponent 注解可以直接注册。@JsonComponent会被自动的扫描到。
例如:

import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*;

@JsonComponent
public class Example {

    public static class Serializer extends JsonSerializer<SomeObject> {
        // ...
    }

    public static class Deserializer extends JsonDeserializer<SomeObject> {
        // ...
    }

}

MessageCodesResolver

SpringMVC 有个策略为直接生成错误码呈现错误消息绑定错误。如果你设置spring.mvc.message-code-resolver.format 的属性 PREFIX_ERROR_CODE 或者 POSTFIX_ERROR_CODE,SpringBoot将会为你创建它。

Static Content (静态内容)

Spring Boot 默认的静态资源在 /static 文件夹内(或者是/public 或者是 /resource)在 classpath 或者是 SerletContext根部。它使用的是Spring MVC的 ResourceHttpRequestHandler 方法,所以你可以通过添加你自己的WebMvcConfigurerAdapter并重写addResourceHandlers方法来修改他的默认行为。

定制图标

ConfigurableWebBingingInitializer

Spring MVC 使用 ConfigurableWebBingingInitializer 去初始化 WebDataBinder 为特定的请求。假如你创建你自己的ConfigurableWebBingingInitializer @Bean, SpringBoot 将会自动的配置SpringMVC 使用它。

模板引擎

错误处理

6. 安全(Security)

假如添加了SpringSecurity 在环境中,那么web应用的默认安全认证是所有HTTP端的。添加方法级的安全你需要添加@EnableGlobalMethodSecurity 注解在你想设置的地方。
默认的security配置实现在 SecurityAutoConfiguration

7. 使用 SQL 数据库

8. 使用NoSQL 数据库

9. 缓存 (Caching)

10. 消息 (Messaging)

11. 调用 REST 服务

12. 验证 (Validation)

13. 发送邮件

14. 用JTA 进行分布式事物

15. Hazelcast

16. Spring 集成( Integration )

17. Spring Session

18. 在JAX监控和管理

19. 测试

20. WebSockets

21. Web Services

22. 创建你自己的自动配置

23. 下一步学习内容

END

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,911评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,014评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,129评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,283评论 1 264
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,159评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,161评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,565评论 3 382
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,251评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,531评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,619评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,383评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,255评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,624评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,916评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,199评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,553评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,756评论 2 335

推荐阅读更多精彩内容