摘要:配置獨(dú)立端口時默認(rèn)情況下和應(yīng)用共用一個,這樣子的話就會直接把應(yīng)用的暴露出去,帶來很大的安全隱患。打開可以看到的繼承結(jié)構(gòu)。最終會把這個加到應(yīng)用的里,來把自己設(shè)置為應(yīng)用的的。這也就是可以生效的原因。
前言
對于一個簡單的Spring boot應(yīng)用,它的spring context是只會有一個。
非web spring boot應(yīng)用,context是AnnotationConfigApplicationContext
web spring boot應(yīng)用,context是AnnotationConfigEmbeddedWebApplicationContext
AnnotationConfigEmbeddedWebApplicationContext是spring boot里自己實(shí)現(xiàn)的一個context,主要功能是啟動embedded servlet container,比如tomcat/jetty。
這個和傳統(tǒng)的war包應(yīng)用不一樣,傳統(tǒng)的war包應(yīng)用有兩個spring context。參考:http://hengyunabc.github.io/s...
但是對于一個復(fù)雜點(diǎn)的spring boot應(yīng)用,它的spring context可能會是多個,下面分析下各種情況。
Demo這個Demo展示不同情況下的spring boot context的繼承情況。
https://github.com/hengyunabc...
配置spring boot actuator/endpoints獨(dú)立端口時spring boot actuator默認(rèn)情況下和應(yīng)用共用一個tomcat,這樣子的話就會直接把應(yīng)用的endpoints暴露出去,帶來很大的安全隱患。
盡管 Spring boot后面默認(rèn)把這個關(guān)掉,需要配置management.security.enabled=false才可以訪問,但是這個還是太危險了。
所以通常都建議把endpoints開在另外一個獨(dú)立的端口上,比如 management.port=8081。
可以增加-Dspring.cloud.bootstrap.enabled=false,來禁止spring cloud,然后啟動Demo。比如
mvn spring-boot:run -Dspring.cloud.bootstrap.enabled=false
然后打開 http://localhost:8080/ 可以看到應(yīng)用的spring context繼承結(jié)構(gòu)。
打開 http://localhost:8081/contexttree 可以看到Management Spring Contex的繼承結(jié)構(gòu)。
可以看到當(dāng)配置management獨(dú)立端口時,management context的parent是應(yīng)用的spring context
相關(guān)的實(shí)現(xiàn)代碼在 org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration 里
在sprig cloud環(huán)境下spring context的情況在有spring cloud時(通常是引入 spring-cloud-starter),因?yàn)閟pring cloud有自己的一套配置初始化機(jī)制,所以它實(shí)際上是自己啟動了一個Spring context,并把自己置為應(yīng)用的context的parent。
spring cloud context的啟動代碼在org.springframework.cloud.bootstrap.BootstrapApplicationListener里。
spring cloud context實(shí)際上是一個特殊的spring boot context,它只掃描BootstrapConfiguration。
ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Use names and ensure unique to protect against duplicates Listnames = 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加到應(yīng)用的spring context里,來把自己設(shè)置為應(yīng)用的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,然后訪問對應(yīng)的url,就可以看到spring context的繼承情況。
如何在應(yīng)用代碼里獲取到 Management Spring Context如果應(yīng)用代碼想獲取到Management Spring Context,可以通過這個bean:org.springframework.boot.actuate.autoconfigure.ManagementContextResolver
spring boot在創(chuàng)建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代碼里獲取應(yīng)用的Spring context
spring boot本身沒有提供方法,應(yīng)用可以自己寫一個@Configuration,保存應(yīng)用的Spring context,然后在endpoints代碼里再取出來。
ApplicationContext.setParent(ApplicationContext) 到底發(fā)生了什么從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里正確判斷事件來源
默認(rèn)情況下,Spring Child Context會收到Parent Context的Event。如果Bean依賴某個Event來做初始化,那么就要判斷好Event是否Bean所在的Context發(fā)出的,否則有可能提前或者多次初始化。
正確的做法是實(shí)現(xiàn)ApplicationContextAware接口,先把context保存起來,在Event里判斷相等時才處理。
public class MyBean implements ApplicationListener總結(jié), 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; } }
當(dāng)配置management.port 為獨(dú)立端口時,Management Spring Context也會是獨(dú)立的context,它的parent是應(yīng)用的spring context
當(dāng)啟動spring cloud時,spring cloud自己會創(chuàng)建出一個spring context,并置為應(yīng)用的context的parent
ApplicationContext.setParent(ApplicationContext) 主要是把parent的environment里的propertySources加到child里
正確處理Spring Event,判斷屬于自己的Context和Event
理解的spring boot context的繼承關(guān)系,能避免一些微妙的spring bean注入的問題,還有不當(dāng)?shù)膕pring context的問題
微信公眾號橫云斷嶺的專欄
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://m.hztianpu.com/yun/72643.html
摘要:的打包結(jié)構(gòu)改動是這個引入的這個的本意是簡化的繼承關(guān)系,以一種直觀的優(yōu)先的方式來實(shí)現(xiàn),同時打包結(jié)構(gòu)和傳統(tǒng)的包應(yīng)用更接近。目前的繼承關(guān)系帶來的一些影響有很多用戶可能會發(fā)現(xiàn),一些代碼在里跑得很好,但是在實(shí)際部署運(yùn)行時不工作。 前言 對spring boot本身啟動原理的分析,請參考:http://hengyunabc.github.io/s... Spring boot里的ClassLoad...
摘要:我們來看可以看到他繼承了我們繼續(xù)來看,這個類有一個方法這個類會幫你掃描那些類自動去添加到程序當(dāng)中。我們看到還有,那我們來看那這塊代碼,就是我們要尋找的內(nèi)置,在這個過程當(dāng)中,我們可以看到創(chuàng)建的一個流程。溫馨提示,文章略長,看完需要耐心!! 今天跟大家來探討下SpringBoot的核心注解@SpringBootApplication以及run方法,理解下springBoot為什么不需要XML,達(dá)...
摘要:本文主要探討的三大核心組件。的核心組件有很多,但真正構(gòu)成其骨骼的,是,和。因此,的核心思想常常被稱作,面向編程。的重要組成部分之一是??偨Y(jié)本文主要總結(jié)了構(gòu)成骨骼框架的三大核心組件及其之間的聯(lián)系,以及對三者實(shí)現(xiàn)原理理解的一些心得體會。 簡介 Spring框架如今已成為服務(wù)端開發(fā)框架中的主流框架之一,是web開發(fā)者的利器。然而,真正讓人著迷的,還是與其實(shí)現(xiàn)相關(guān)的 原理,設(shè)計模式以及許多工...
摘要:設(shè)置應(yīng)用上線文初始化器的作用是什么源碼如下。來看下方法源碼,其實(shí)就是初始化一個應(yīng)用上下文初始化器實(shí)例的集合。設(shè)置監(jiān)聽器和設(shè)置初始化器調(diào)用的方法是一樣的,只是傳入的類型不一樣,設(shè)置監(jiān)聽器的接口類型為,對應(yīng)的文件配置內(nèi)容請見下方。 Spring Boot 的應(yīng)用教程我們已經(jīng)分享過很多了,今天來通過源碼來分析下它的啟動過程,探究下 Spring Boot 為什么這么簡便的奧秘。 本篇基于 S...
閱讀 2434·2021-11-24 10:31
閱讀 3488·2021-11-23 09:51
閱讀 2331·2021-11-15 18:11
閱讀 2454·2021-09-02 15:15
閱讀 2519·2019-08-29 17:02
閱讀 2350·2019-08-29 15:04
閱讀 911·2019-08-29 12:27
閱讀 2925·2019-08-28 18:15