资讯专栏INFORMATION COLUMN

深入Spring Boot:Spring Context的继承关系和影响

tuantuan / 3472人阅读

摘要:配置独立端口时默认情况下和应用共用一个,这样子的话就会直接把应用的暴露出去,带来很大的安全隐患。打开可以看到的继承结构。最终会把这个加到应用的里,来把自己设置为应用的的。这也就是可以生效的原因。

前言

对于一个简单的Spring boot应用,它的spring context是只会有一个。

非web spring boot应用,context是AnnotationConfigApplicationContext

web spring boot应用,context是AnnotationConfigEmbeddedWebApplicationContext

AnnotationConfigEmbeddedWebApplicationContext是spring boot里自己实现的一个context,主要功能是启动embedded servlet container,比如tomcat/jetty。

这个和传统的war包应用不一样,传统的war包应用有两个spring context。参考:http://hengyunabc.github.io/s...

但是对于一个复杂点的spring boot应用,它的spring context可能会是多个,下面分析下各种情况。

Demo

这个Demo展示不同情况下的spring boot context的继承情况。

https://github.com/hengyunabc...

配置spring boot actuator/endpoints独立端口时

spring boot actuator默认情况下和应用共用一个tomcat,这样子的话就会直接把应用的endpoints暴露出去,带来很大的安全隐患。

尽管 Spring boot后面默认把这个关掉,需要配置management.security.enabled=false才可以访问,但是这个还是太危险了。

所以通常都建议把endpoints开在另外一个独立的端口上,比如 management.port=8081

可以增加-Dspring.cloud.bootstrap.enabled=false,来禁止spring cloud,然后启动Demo。比如

mvn spring-boot:run -Dspring.cloud.bootstrap.enabled=false

然后打开 http://localhost:8080/ 可以看到应用的spring context继承结构。

打开 http://localhost:8081/contexttree 可以看到Management Spring Contex的继承结构。

可以看到当配置management独立端口时,management context的parent是应用的spring context

相关的实现代码在 org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration

在sprig cloud环境下spring context的情况

在有spring cloud时(通常是引入 spring-cloud-starter),因为spring cloud有自己的一套配置初始化机制,所以它实际上是自己启动了一个Spring context,并把自己置为应用的context的parent。

spring cloud context的启动代码在org.springframework.cloud.bootstrap.BootstrapApplicationListener里。

spring cloud context实际上是一个特殊的spring boot context,它只扫描BootstrapConfiguration

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
List names = SpringFactoriesLoader
    .loadFactoryNames(BootstrapConfiguration.class, classLoader);
for (String name : StringUtils.commaDelimitedListToStringArray(
    environment.getProperty("spring.cloud.bootstrap.sources", ""))) {
  names.add(name);
}
// TODO: is it possible or sensible to share a ResourceLoader?
SpringApplicationBuilder builder = new SpringApplicationBuilder()
    .profiles(environment.getActiveProfiles()).bannerMode(Mode.OFF)
    .environment(bootstrapEnvironment)
    .properties("spring.application.name:" + configName)
    .registerShutdownHook(false).logStartupInfo(false).web(false);
List> sources = new ArrayList<>();

最终会把这个ParentContextApplicationContextInitializer加到应用的spring context里,来把自己设置为应用的context的parent。

public class ParentContextApplicationContextInitializer implements
        ApplicationContextInitializer, Ordered {
    private int order = Ordered.HIGHEST_PRECEDENCE;
    private final ApplicationContext parent;
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        if (applicationContext != this.parent) {
            applicationContext.setParent(this.parent);
            applicationContext.addApplicationListener(EventPublisher.INSTANCE);
        }
    }

和上面一样,直接启动demo,不要配置-Dspring.cloud.bootstrap.enabled=false,然后访问对应的url,就可以看到spring context的继承情况。

如何在应用代码里获取到 Management Spring Context

如果应用代码想获取到Management Spring Context,可以通过这个bean:org.springframework.boot.actuate.autoconfigure.ManagementContextResolver

spring boot在创建Management Spring Context时,就会保存到ManagementContextResolver里。

@Configuration
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
@ConditionalOnWebApplication
@AutoConfigureAfter({ PropertyPlaceholderAutoConfiguration.class,
        EmbeddedServletContainerAutoConfiguration.class, WebMvcAutoConfiguration.class,
        ManagementServerPropertiesAutoConfiguration.class,
        RepositoryRestMvcAutoConfiguration.class, HypermediaAutoConfiguration.class,
        HttpMessageConvertersAutoConfiguration.class })
public class EndpointWebMvcAutoConfiguration
        implements ApplicationContextAware, BeanFactoryAware, SmartInitializingSingleton {
      @Bean
        public ManagementContextResolver managementContextResolver() {
            return new ManagementContextResolver(this.applicationContext);
        }

        @Bean
        public ManagementServletContext managementServletContext(
                final ManagementServerProperties properties) {
            return new ManagementServletContext() {

                @Override
                public String getContextPath() {
                    return properties.getContextPath();
                }

            };
        }
如何在Endpoints代码里获取应用的Spring context

spring boot本身没有提供方法,应用可以自己写一个@Configuration,保存应用的Spring context,然后在endpoints代码里再取出来。

ApplicationContext.setParent(ApplicationContext) 到底发生了什么

从spring的代码就可以看出来,主要是把parent的environment里的propertySources加到child里。这也就是spring cloud config可以生效的原因。

// org.springframework.context.support.AbstractApplicationContext.setParent(ApplicationContext)
/**
 * Set the parent of this application context.
 * 

The parent {@linkplain ApplicationContext#getEnvironment() environment} is * {@linkplain ConfigurableEnvironment#merge(ConfigurableEnvironment) merged} with * this (child) application context environment if the parent is non-{@code null} and * its environment is an instance of {@link ConfigurableEnvironment}. * @see ConfigurableEnvironment#merge(ConfigurableEnvironment) */ @Override public void setParent(ApplicationContext parent) { this.parent = parent; if (parent != null) { Environment parentEnvironment = parent.getEnvironment(); if (parentEnvironment instanceof ConfigurableEnvironment) { getEnvironment().merge((ConfigurableEnvironment) parentEnvironment); } } }

// org.springframework.core.env.AbstractEnvironment.merge(ConfigurableEnvironment)

@Override
public void merge(ConfigurableEnvironment parent) {
  for (PropertySource ps : parent.getPropertySources()) {
    if (!this.propertySources.contains(ps.getName())) {
      this.propertySources.addLast(ps);
    }
  }
  String[] parentActiveProfiles = parent.getActiveProfiles();
  if (!ObjectUtils.isEmpty(parentActiveProfiles)) {
    synchronized (this.activeProfiles) {
      for (String profile : parentActiveProfiles) {
        this.activeProfiles.add(profile);
      }
    }
  }
  String[] parentDefaultProfiles = parent.getDefaultProfiles();
  if (!ObjectUtils.isEmpty(parentDefaultProfiles)) {
    synchronized (this.defaultProfiles) {
      this.defaultProfiles.remove(RESERVED_DEFAULT_PROFILE_NAME);
      for (String profile : parentDefaultProfiles) {
        this.defaultProfiles.add(profile);
      }
    }
  }
}
怎样在Spring Event里正确判断事件来源

默认情况下,Spring Child Context会收到Parent Context的Event。如果Bean依赖某个Event来做初始化,那么就要判断好Event是否Bean所在的Context发出的,否则有可能提前或者多次初始化。

正确的做法是实现ApplicationContextAware接口,先把context保存起来,在Event里判断相等时才处理。

public class MyBean implements ApplicationListener, ApplicationContextAware {
    private ApplicationContext context;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().equals(context)) {
            // do something
        }
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
总结

当配置management.port 为独立端口时,Management Spring Context也会是独立的context,它的parent是应用的spring context

当启动spring cloud时,spring cloud自己会创建出一个spring context,并置为应用的context的parent

ApplicationContext.setParent(ApplicationContext) 主要是把parent的environment里的propertySources加到child里

正确处理Spring Event,判断属于自己的Context和Event

理解的spring boot context的继承关系,能避免一些微妙的spring bean注入的问题,还有不当的spring context的问题

微信公众号

横云断岭的专栏

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72643.html

相关文章

  • 深入Spring Boot:ClassLoader继承关系影响

    摘要:的打包结构改动是这个引入的这个的本意是简化的继承关系,以一种直观的优先的方式来实现,同时打包结构和传统的包应用更接近。目前的继承关系带来的一些影响有很多用户可能会发现,一些代码在里跑得很好,但是在实际部署运行时不工作。 前言 对spring boot本身启动原理的分析,请参考:http://hengyunabc.github.io/s... Spring boot里的ClassLoad...

    lifesimple 评论0 收藏0
  • 深入SpringBoot核心注解原理

    摘要:我们来看可以看到他继承了我们继续来看,这个类有一个方法这个类会帮你扫描那些类自动去添加到程序当中。我们看到还有,那我们来看那这块代码,就是我们要寻找的内置,在这个过程当中,我们可以看到创建的一个流程。温馨提示,文章略长,看完需要耐心!! 今天跟大家来探讨下SpringBoot的核心注解@SpringBootApplication以及run方法,理解下springBoot为什么不需要XML,达...

    CoderBear 评论0 收藏0
  • 2.走向自动装配

    摘要:走向自动装配模式注解装配走向自动装配课程介绍手动装配自动装配自动装配是以手动装配为基础实现的手动装配模式注解模式注解是一种用于声明在应用中扮演组件角色的注解。 2.走向自动装配 Spring 模式注解装配 2-1 走向自动装配 课程介绍 spring framework手动装配 spring boot自动装配 spring boot自动装配是以spring framework手动装...

    rose 评论0 收藏0
  • Spring核心组件剖析

    摘要:本文主要探讨的三大核心组件。的核心组件有很多,但真正构成其骨骼的,是,和。因此,的核心思想常常被称作,面向编程。的重要组成部分之一是。总结本文主要总结了构成骨骼框架的三大核心组件及其之间的联系,以及对三者实现原理理解的一些心得体会。 简介 Spring框架如今已成为服务端开发框架中的主流框架之一,是web开发者的利器。然而,真正让人着迷的,还是与其实现相关的 原理,设计模式以及许多工...

    springDevBird 评论0 收藏0
  • Spring Boot 2.x 启动全过程源码分析(上)入口类剖析

    摘要:设置应用上线文初始化器的作用是什么源码如下。来看下方法源码,其实就是初始化一个应用上下文初始化器实例的集合。设置监听器和设置初始化器调用的方法是一样的,只是传入的类型不一样,设置监听器的接口类型为,对应的文件配置内容请见下方。 Spring Boot 的应用教程我们已经分享过很多了,今天来通过源码来分析下它的启动过程,探究下 Spring Boot 为什么这么简便的奥秘。 本篇基于 S...

    MobService 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<