private void addPropertySource(PropertySource<?> propertySource) { String name = propertySource.getName(); MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources(); PropertySource<?> existing = propertySources.get(name); if (existing != null) { PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ? composite.addPropertySource(newSource); composite.addPropertySource(existing); propertySources.replace(name, composite); propertySources.addLast(propertySource); propertySources.addBefore(firstProcessed, propertySource);
@Override public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication application) { env.getPropertySources().addFirst(new MapPropertySource("gateway-properties", Collections.singletonMap("spring.webflux.hiddenmethod.filter.enabled", "false"))); } }
/** * Initialize Apollo Configurations Just after environment is ready. * * @param environment */ protected void initialize(ConfigurableEnvironment environment) { if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) { //already initialized return; } String namespaces = environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, ConfigConsts.NAMESPACE_APPLICATION); logger.debug("Apollo bootstrap namespaces: {}", namespaces); List<String> namespaceList = NAMESPACE_SPLITTER.splitToList(namespaces); CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME); for (String namespace : namespaceList) { Config config = ConfigService.getConfig(namespace); composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config)); } environment.getPropertySources().addFirst(composite); }
private void ensureBootstrapPropertyPrecedence(ConfigurableEnvironment environment) { MutablePropertySources propertySources = environment.getPropertySources(); PropertySource<?> bootstrapPropertySource = propertySources .get(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME); // not exists or already in the first place if (bootstrapPropertySource == null || propertySources.precedenceOf(bootstrapPropertySource) == 0) { return; } propertySources.remove(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME); propertySources.addFirst(bootstrapPropertySource); }
/** * Replace {@code Servlet}-based {@link StubPropertySource stub property sources} with * actual instances populated with the given {@code servletContext} and * {@code servletConfig} objects. * <p>This method is idempotent with respect to the fact it may be called any number * of times but will perform replacement of stub property sources with their * corresponding actual property sources once and only once. * @param sources the {@link MutablePropertySources} to initialize (must not * be {@code null}) * @param servletContext the current {@link ServletContext} (ignored if {@code null} * or if the {@link StandardServletEnvironment#SERVLET_CONTEXT_PROPERTY_SOURCE_NAME * servlet context property source} has already been initialized) * @param servletConfig the current {@link ServletConfig} (ignored if {@code null} * or if the {@link StandardServletEnvironment#SERVLET_CONFIG_PROPERTY_SOURCE_NAME * servlet config property source} has already been initialized) * @see org.springframework.core.env.PropertySource.StubPropertySource * @see org.springframework.core.env.ConfigurableEnvironment#getPropertySources() */ public static void initServletPropertySources(MutablePropertySources sources, @Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) { Assert.notNull(sources, "'propertySources' must not be null"); String name = StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME; if (servletContext != null && sources.contains(name) && sources.get(name) instanceof StubPropertySource) { sources.replace(name, new ServletContextPropertySource(name, servletContext)); } name = StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME; if (servletConfig != null && sources.contains(name) && sources.get(name) instanceof StubPropertySource) { sources.replace(name, new ServletConfigPropertySource(name, servletConfig)); } }
@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); } } } }
public static GenericXmlApplicationContext setupContext() { final GenericXmlApplicationContext context = new GenericXmlApplicationContext(); if (System.getProperty(AVAILABLE_SERVER_SOCKET) == null) { System.out.print("Detect open server socket..."); int availableServerSocket = SocketUtils.findAvailableTcpPort(5678); final Map<String, Object> sockets = new HashMap<>(); sockets.put(AVAILABLE_SERVER_SOCKET, availableServerSocket); final MapPropertySource propertySource = new MapPropertySource("sockets", sockets); context.getEnvironment().getPropertySources().addLast(propertySource); } System.out.println("using port " + context.getEnvironment().getProperty(AVAILABLE_SERVER_SOCKET)); context.load("classpath:META-INF/spring/integration/tcpClientServerDemo-context.xml"); context.registerShutdownHook(); context.refresh(); return context; }
@Override protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) { int availableServerSocket = SocketUtils.findAvailableTcpPort(5678); final Map<String, Object> sockets = new HashMap<String, Object>(); sockets.put("availableServerSocket", availableServerSocket); if (LOGGER.isInfoEnabled()) { LOGGER.info("Available Server Socket: " + availableServerSocket); } final MapPropertySource propertySource = new MapPropertySource("sockets", sockets); context.getEnvironment().getPropertySources().addLast(propertySource); super.loadBeanDefinitions(context, mergedConfig); }
/** * Add, remove or re-order any {@link PropertySource}s in this application's * environment. * @param environment this application's environment * @param args arguments passed to the {@code run} method * @see #configureEnvironment(ConfigurableEnvironment, String[]) */ protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) { sources.addLast( new MapPropertySource("defaultProperties", this.defaultProperties)); } if (this.addCommandLineProperties && args.length > 0) { String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME; if (sources.contains(name)) { PropertySource<?> source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); composite.addPropertySource(new SimpleCommandLinePropertySource( "springApplicationCommandLineArgs", args)); composite.addPropertySource(source); sources.replace(name, composite); } else { sources.addFirst(new SimpleCommandLinePropertySource(args)); } } }
private StandardEnvironment copyEnvironment(ConfigurableEnvironment input) { StandardEnvironment environment = new StandardEnvironment(); MutablePropertySources capturedPropertySources = environment.getPropertySources(); // Only copy the default property source(s) and the profiles over from the main // environment (everything else should be pristine, just like it was on startup). for (String name : DEFAULT_PROPERTY_SOURCES) { if (input.getPropertySources().contains(name)) { if (capturedPropertySources.contains(name)) { capturedPropertySources.replace(name, input.getPropertySources().get(name)); } else { capturedPropertySources.addLast(input.getPropertySources().get(name)); } } } environment.setActiveProfiles(input.getActiveProfiles()); environment.setDefaultProfiles(input.getDefaultProfiles()); Map<String, Object> map = new HashMap<String, Object>(); map.put("spring.jmx.enabled", false); map.put("spring.main.sources", ""); capturedPropertySources .addFirst(new MapPropertySource(REFRESH_ARGS_PROPERTY_SOURCE, map)); return environment; }
@Override public void initialize(ConfigurableApplicationContext applicationContext) { ConfigurableEnvironment environment = applicationContext.getEnvironment(); environment.getPropertySources().addFirst(new PropertySource<Object>("testPropertySource") { @Override public Object getProperty(String key) { return "name".equals(key) ? "testName" : null; } }); } }
MutablePropertySources propertySources = environment.getPropertySources(); assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME), is(true)); assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME), is(true)); assertThat(environment.getProperty("pCommon"), is("pCommonConfigValue")); assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), lessThan(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)))); assertThat(environment.getProperty("pContext1"), is("pContext1Value")); assertThat(environment.getProperty("pConfig1"), is("pConfig1Value")); assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), lessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)))); mockSystemProperties.setProperty("pCommon", "pCommonSysPropsValue"); mockSystemProperties.setProperty("pSysProps1", "pSysProps1Value"); propertySources.replace(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, mockSystemProperties);
@SuppressWarnings("unchecked") private void setPortProperty(ConfigurableEnvironment environment, String propertyName, int port) { MutablePropertySources sources = environment.getPropertySources(); PropertySource<?> source = sources.get("server.ports"); if (source == null) { source = new MapPropertySource("server.ports", new HashMap<>()); sources.addFirst(source); } ((Map<String, Object>) source.getSource()).put(propertyName, port); }
environment.getPropertySources().get(INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); if (ps == null) { ps = new MapPropertySource(INLINED_PROPERTIES_PROPERTY_SOURCE_NAME, new LinkedHashMap<>()); environment.getPropertySources().addFirst(ps); ps.getSource().putAll(convertInlinedPropertiesToMap(inlinedProperties));
@Test public void withImplicitName() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigWithImplicitName.class); ctx.refresh(); assertTrue("property source p1 was not added", ctx.getEnvironment().getPropertySources().contains("class path resource [org/springframework/context/annotation/p1.properties]")); assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); }
private void defaultProperties(ConfigurableApplicationContext context) { MutablePropertySources sources = context.getEnvironment().getPropertySources(); if (!sources.contains(DEFAULT_PROPERTIES)) { sources.addLast( new MapPropertySource(DEFAULT_PROPERTIES, Collections.emptyMap())); } @SuppressWarnings("unchecked") Map<String, Object> source = (Map<String, Object>) sources.get(DEFAULT_PROPERTIES) .getSource(); Map<String, Object> map = new HashMap<>(source); map.put(SPRING_FUNCTIONAL_ENABLED, "true"); map.put(SPRING_WEB_APPLICATION_TYPE, getWebApplicationType()); sources.replace(DEFAULT_PROPERTIES, new MapPropertySource(DEFAULT_PROPERTIES, map)); }
private void reorderSources(ConfigurableEnvironment environment) { PropertySource<?> removed = environment.getPropertySources() .remove(DEFAULT_PROPERTIES); if (removed instanceof ExtendedDefaultPropertySource) { ExtendedDefaultPropertySource defaultProperties = (ExtendedDefaultPropertySource) removed; environment.getPropertySources().addLast(new MapPropertySource( DEFAULT_PROPERTIES, defaultProperties.getSource())); for (PropertySource<?> source : defaultProperties.getPropertySources() .getPropertySources()) { if (!environment.getPropertySources().contains(source.getName())) { environment.getPropertySources().addBefore(DEFAULT_PROPERTIES, source); } } } }
@Test public void addActiveProfile_whenActiveProfilesPropertyIsAlreadySet() { ConfigurableEnvironment env = new StandardEnvironment(); assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME), nullValue()); env.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1")); assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME), equalTo("p1")); env.addActiveProfile("p2"); assertThat(env.getActiveProfiles(), arrayContaining("p1", "p2")); }
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); if (!environment.resolvePlaceholders("${spring.cloud.config.enabled:false}") .equalsIgnoreCase("true")) { if (!environment.getPropertySources().contains(this.propertySource.getName())) { environment.getPropertySources().addLast(this.propertySource); } } }
/** * Copy from {@link BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)} * * @param propertySources {@link MutablePropertySources} * @param map Default RocketMQ Bus Properties */ private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) { MapPropertySource target = null; if (propertySources.contains(PROPERTY_SOURCE_NAME)) { PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME); if (source instanceof MapPropertySource) { target = (MapPropertySource) source; for (String key : map.keySet()) { if (!target.containsProperty(key)) { target.getSource().put(key, map.get(key)); } } } } if (target == null) { target = new MapPropertySource(PROPERTY_SOURCE_NAME, map); } if (!propertySources.contains(PROPERTY_SOURCE_NAME)) { propertySources.addLast(target); } }