开发者社区> 横云断岭> 正文

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

简介: 前言 对于一个简单的Spring boot应用,它的spring context是只会有一个。 非web spring boot应用,context是AnnotationConfigApplicationContext...
+关注继续查看

前言

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

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

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

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

Demo

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

https://github.com/hengyunabc/spring-boot-inside/tree/master/demo-classloader-context

配置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<String> 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<Class<?>> sources = new ArrayList<>();

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

public class ParentContextApplicationContextInitializer implements
        ApplicationContextInitializer<ConfigurableApplicationContext>, 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.
 * <p>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);
      }
    }
  }
}

总结

  • 当配置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 boot context的继承关系,能避免一些微妙的spring bean注入的问题,还有不当的spring context的问题

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
玩“公主焊接”,顺便学习学习数据库关系映射与Spring Boot中MyBatis(SSM框架)的级联操作(bushi)
玩“公主焊接”,顺便学习学习数据库关系映射与Spring Boot中MyBatis(SSM框架)的级联操作(bushi)
83 0
Spring Boot AOP - 面向切面编程
Spring Boot AOP - 面向切面编程
116 0
Spring Boot中的校验-Validation的使用
Spring Boot中的校验-Validation的使用
69 0
Spring Boot发送邮件以及阿里云服务器无法发送邮件的问题解决
Spring Boot发送邮件以及阿里云服务器无法发送邮件的问题解决
115 0
Spring Boot实现文件上传
Spring Boot实现文件上传
109 0
Spring Boot资源文件问题总结(Spring Boot的静态资源访问,配置文件外置)
Spring Boot资源文件问题总结(Spring Boot的静态资源访问,配置文件外置)
287 0
Certbot生成Lets Encrypt免费证书并配置到Spring Boot
Certbot生成Lets Encrypt免费证书并配置到Spring Boot
166 0
Spring Boot中的Mybatis分页插件-pagehelper的使用
Spring Boot中的Mybatis分页插件-pagehelper的使用
97 0
一招学会—Spring Boot使用PageHelper进行分页
一招学会—Spring Boot使用PageHelper进行分页
124 0
Spring boot 使用 ON DUPLICATE KEY UPDATE属性控制版本 更新数据不成功
如果更新不成功会报下面的错误(此错误是自定义的): The data you want to update has been updated by another user. Please reopen and try again! 一、主要按下面的流程检查: 1、检查数据库的段alastupdatetime定义 2、检查.xml的alastupdatetime 3、要更新数据的主键是否在同一个updateByBatch中的List中重复出现
91 0
+关注
横云断岭
负责7K+应用,100K+机器的Spring Boot微服务技术落地,关注开发体验,微服务,APM,应用诊断技术。Dubbo/Arthas开源。 github: https://github.com/hengyunabc
文章
问答
文章排行榜
最热
最新
相关电子书
更多
电商网站需求分析和架构设计Spring Boot2.6入门
立即下载
云上Docker的Spring Cloud微服务应用实践分享
立即下载
Spring Boot 2.6.0电商网站开发实战
立即下载