Java Code Examples for org.springframework.context.ApplicationContext#getParent()

The following examples show how to use org.springframework.context.ApplicationContext#getParent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BeanDefinitionUtils.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a bean definition for the specified bean name. If the parent context of the current context contains a
 * bean definition with the same name, the definition is created as a bean copy of the parent definition. This
 * method is useful for config parsers that want to create a bean definition from configuration but also want to
 * retain the default properties of the original bean.
 *
 * @param applicationContext    the current application context
 * @param beanName
 * @return the bean definition
 */
public static BeanDefinition createBeanDefinitionFromOriginal(ApplicationContext applicationContext,
                                                              String beanName) {
    ApplicationContext parentContext = applicationContext.getParent();
    BeanDefinition parentDefinition = null;

    if (parentContext != null &&
        parentContext.getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) {
        ConfigurableListableBeanFactory parentBeanFactory = (ConfigurableListableBeanFactory)parentContext
            .getAutowireCapableBeanFactory();

        try {
            parentDefinition = parentBeanFactory.getBeanDefinition(beanName);
        } catch (NoSuchBeanDefinitionException e) {}
    }

    if (parentDefinition != null) {
        return new GenericBeanDefinition(parentDefinition);
    } else {
        return new GenericBeanDefinition();
    }
}
 
Example 2
Source File: DefaultMockMvcBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected WebApplicationContext initWebAppContext() {
	ServletContext servletContext = this.webAppContext.getServletContext();
	Assert.state(servletContext != null, "No ServletContext");
	ApplicationContext rootWac = WebApplicationContextUtils.getWebApplicationContext(servletContext);

	if (rootWac == null) {
		rootWac = this.webAppContext;
		ApplicationContext parent = this.webAppContext.getParent();
		while (parent != null) {
			if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) {
				rootWac = parent;
				break;
			}
			parent = parent.getParent();
		}
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, rootWac);
	}

	return this.webAppContext;
}
 
Example 3
Source File: GaugeRegistry4SpringContext.java    From metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
    //仅在root application context启动后执行
    if (applicationContext.getParent() != null) {
        return;
    }
    Map<String, Object> beansOfType = applicationContext.getBeansOfType(Object.class);
    for (Object bean : beansOfType.values()) {
        if (bean == null) {
            return;
        }
        Class<?> targetClass = AopUtils.getTargetClass(bean);
        Method[] methods = targetClass.getMethods();
        if (methods == null || methods.length == 0) {
            return;
        }
        for (Method method : methods) {
            EnableGauge aliGaugeAnnotation = method.getAnnotation(EnableGauge.class);
            if (aliGaugeAnnotation == null) {
                continue;
            }
            GaugeRegistry.registerGauge(aliGaugeAnnotation, bean, method);
        }
    }
}
 
Example 4
Source File: DispatcherWacRootWacEarTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void verifyDispatcherWacConfig() {
	ApplicationContext parent = wac.getParent();
	assertNotNull(parent);
	assertTrue(parent instanceof WebApplicationContext);

	ApplicationContext grandParent = parent.getParent();
	assertNotNull(grandParent);
	assertFalse(grandParent instanceof WebApplicationContext);

	ServletContext dispatcherServletContext = wac.getServletContext();
	assertNotNull(dispatcherServletContext);
	ServletContext rootServletContext = ((WebApplicationContext) parent).getServletContext();
	assertNotNull(rootServletContext);
	assertSame(dispatcherServletContext, rootServletContext);

	assertSame(parent,
		rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
	assertSame(parent,
		dispatcherServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));

	assertEquals("ear", ear);
	assertEquals("root", root);
	assertEquals("dispatcher", dispatcher);
}
 
Example 5
Source File: SpringBus.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void onApplicationEvent(ApplicationEvent event) {
    if (ctx == null) {
        return;
    }
    boolean doIt = false;
    ApplicationContext ac = ctx;
    while (ac != null) {
        if (event.getSource() == ac) {
            doIt = true;
            break;
        }
        ac = ac.getParent();
    }
    if (doIt) {
        if (event instanceof ContextRefreshedEvent) {
            if (getState() != BusState.RUNNING) {
                initialize();
            }
        } else if (event instanceof ContextClosedEvent && getState() == BusState.RUNNING) {
            // The bus could be create by using SpringBusFactory.createBus("/cxf.xml");
            // Just to make sure the shutdown is called rightly
            shutdown();
        }
    }
}
 
Example 6
Source File: ConfigurationPropertiesBeans.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext)
		throws BeansException {
	this.applicationContext = applicationContext;
	if (applicationContext
			.getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) {
		this.beanFactory = (ConfigurableListableBeanFactory) applicationContext
				.getAutowireCapableBeanFactory();
	}
	if (applicationContext.getParent() != null && applicationContext.getParent()
			.getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) {
		ConfigurableListableBeanFactory listable = (ConfigurableListableBeanFactory) applicationContext
				.getParent().getAutowireCapableBeanFactory();
		String[] names = listable
				.getBeanNamesForType(ConfigurationPropertiesBeans.class);
		if (names.length == 1) {
			this.parent = (ConfigurationPropertiesBeans) listable.getBean(names[0]);
			this.beans.putAll(this.parent.beans);
		}
	}
}
 
Example 7
Source File: DispatcherWacRootWacEarTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyDispatcherWacConfig() {
	ApplicationContext parent = wac.getParent();
	assertNotNull(parent);
	assertTrue(parent instanceof WebApplicationContext);

	ApplicationContext grandParent = parent.getParent();
	assertNotNull(grandParent);
	assertFalse(grandParent instanceof WebApplicationContext);

	ServletContext dispatcherServletContext = wac.getServletContext();
	assertNotNull(dispatcherServletContext);
	ServletContext rootServletContext = ((WebApplicationContext) parent).getServletContext();
	assertNotNull(rootServletContext);
	assertSame(dispatcherServletContext, rootServletContext);

	assertSame(parent,
		rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
	assertSame(parent,
		dispatcherServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));

	assertEquals("ear", ear);
	assertEquals("root", root);
	assertEquals("dispatcher", dispatcher);
}
 
Example 8
Source File: DefaultMockMvcBuilder.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected WebApplicationContext initWebAppContext() {

	ServletContext servletContext = this.webAppContext.getServletContext();
	ApplicationContext rootWac = WebApplicationContextUtils.getWebApplicationContext(servletContext);

	if (rootWac == null) {
		rootWac = this.webAppContext;
		ApplicationContext parent = this.webAppContext.getParent();
		while (parent != null) {
			if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) {
				rootWac = parent;
				break;
			}
			parent = parent.getParent();
		}
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, rootWac);
	}

	return this.webAppContext;
}
 
Example 9
Source File: RestartEndpoint.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private void close() {
	ApplicationContext context = this.context;
	while (context instanceof Closeable) {
		try {
			((Closeable) context).close();
		}
		catch (IOException e) {
			logger.error("Cannot close context: " + context.getId(), e);
		}
		context = context.getParent();
	}
}
 
Example 10
Source File: EnvironmentDecryptApplicationInitializer.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private void insert(ApplicationContext applicationContext,
		PropertySource<?> propertySource) {
	ApplicationContext parent = applicationContext;
	while (parent != null) {
		if (parent.getEnvironment() instanceof ConfigurableEnvironment) {
			ConfigurableEnvironment mutable = (ConfigurableEnvironment) parent
					.getEnvironment();
			insert(mutable.getPropertySources(), propertySource);
		}
		parent = parent.getParent();
	}
}
 
Example 11
Source File: NettyServerPortInfoApplicaitonInitializer.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
private void setPortProperty(ApplicationContext context, String propertyName, int port) {
  if (context instanceof ConfigurableApplicationContext) {
    setPortProperty(((ConfigurableApplicationContext) context).getEnvironment(),
        propertyName, port);
  }
  if (context.getParent() != null) {
    setPortProperty(context.getParent(), propertyName, port);
  }
}
 
Example 12
Source File: ApplicationContextListener.java    From jwala with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of the spring event listener interface.
 *
 * @param event the spring event from the application
 */
@EventListener
public void handleEvent(ApplicationEvent event) {
    // checking for start up event
    // order of events is BrokerAvailabilityEvent -> ContextRefreshedEvent[parent=null] -> ContextRefreshedEvent[with non-null parent]
    // so wait until the latest event is received: ContextRefreshedEvent[with non-null parent]

    // skip the BrokerAvailabilityEvent, and ignore all other events (SessionConnectedEvent, ServletRequestHandledEvent, ContextClosedEvent, etc.)
    if (!(event instanceof ContextRefreshedEvent)) {
        LOGGER.debug("Expecting ContextRefreshedEvent. Skipping.");
        return;
    }

    LOGGER.info("Received ContextRefreshedEvent {}", event);

    ContextRefreshedEvent crEvent = (ContextRefreshedEvent) event;
    final ApplicationContext applicationContext = crEvent.getApplicationContext();
    // skip the ContextRefreshedEvent[parent=null] but check for non-null context first
    if (null == applicationContext) {
        LOGGER.debug("Expecting non-null ApplicationContext. Skipping.");
        return;
    }
    if (null == applicationContext.getParent()) {
        LOGGER.debug("Expecting non-null ApplicationContext parent. Skipping.");
        return;
    }

    processBootstrapConfiguration();
}
 
Example 13
Source File: NacosConfigAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Bean
public NacosConfigProperties nacosConfigProperties(ApplicationContext context) {
	if (context.getParent() != null
			&& BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
					context.getParent(), NacosConfigProperties.class).length > 0) {
		return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(),
				NacosConfigProperties.class);
	}
	return new NacosConfigProperties();
}
 
Example 14
Source File: SpringPostProcessor.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();

    if (applicationContext.getParent() == null) {
        FactoryBuilder.registerBeanFactory(applicationContext.getBean(BeanFactory.class));
    }
}
 
Example 15
Source File: ConfigClientAutoConfiguration.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Bean
public ConfigClientProperties configClientProperties(Environment environment,
		ApplicationContext context) {
	if (context.getParent() != null
			&& BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
					context.getParent(), ConfigClientProperties.class).length > 0) {
		return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(),
				ConfigClientProperties.class);
	}
	ConfigClientProperties client = new ConfigClientProperties(environment);
	return client;
}
 
Example 16
Source File: SpringBus.java    From cxf with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc}*/
public void setApplicationContext(ApplicationContext applicationContext) {
    ctx = (AbstractApplicationContext)applicationContext;
    @SuppressWarnings("rawtypes")
    ApplicationListener listener = new ApplicationListener() {
        public void onApplicationEvent(ApplicationEvent event) {
            SpringBus.this.onApplicationEvent(event);
        }
    };
    ctx.addApplicationListener(listener);
    ApplicationContext ac = applicationContext.getParent();
    while (ac != null) {
        if (ac instanceof AbstractApplicationContext) {
            ((AbstractApplicationContext)ac).addApplicationListener(listener);
        }
        ac = ac.getParent();
    }

    // set the classLoader extension with the application context classLoader
    setExtension(applicationContext.getClassLoader(), ClassLoader.class);

    setExtension(new ConfigurerImpl(applicationContext), Configurer.class);

    ResourceManager m = getExtension(ResourceManager.class);
    m.addResourceResolver(new BusApplicationContextResourceResolver(applicationContext));

    setExtension(applicationContext, ApplicationContext.class);
    ConfiguredBeanLocator loc = getExtension(ConfiguredBeanLocator.class);
    if (!(loc instanceof SpringBeanLocator)) {
        setExtension(new SpringBeanLocator(applicationContext, this), ConfiguredBeanLocator.class);
    }
    if (getState() != BusState.RUNNING) {
        initialize();
    }
}
 
Example 17
Source File: EnvironmentDecryptApplicationInitializer.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private void removeDecryptedProperties(ApplicationContext applicationContext) {
	ApplicationContext parent = applicationContext;
	while (parent != null) {
		if (parent.getEnvironment() instanceof ConfigurableEnvironment) {
			((ConfigurableEnvironment) parent.getEnvironment()).getPropertySources()
					.remove(DECRYPTED_PROPERTY_SOURCE_NAME);
		}
		parent = parent.getParent();
	}
}
 
Example 18
Source File: ContextUtils.java    From spring-boot-inside with MIT License 4 votes vote down vote up
public static String treeHtml(ApplicationContext context) {

		StringBuilder result = new StringBuilder();

		result.append("<ul>");

		result.append("<li>" + context.toString() + "</li>");

		while (context.getParent() != null) {
			context = context.getParent();
			result.append("<li>" + context.toString() + "</li>");
		}

		result.append("</ul>");
		return result.toString();
	}
 
Example 19
Source File: ApplicationContextHolder.java    From mPass with Apache License 2.0 4 votes vote down vote up
public static void setApplicationContext(ApplicationContext context) {
    if (applicationContext == null
            || applicationContext == context.getParent()) {
        applicationContext = context;
    }
}
 
Example 20
Source File: ApplicationContextHolder.java    From mPaaS with Apache License 2.0 4 votes vote down vote up
public static void setApplicationContext(ApplicationContext context) {
    if (applicationContext == null
            || applicationContext == context.getParent()) {
        applicationContext = context;
    }
}