org.springframework.context.support.AbstractApplicationContext Java Examples

The following examples show how to use org.springframework.context.support.AbstractApplicationContext. 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: SecurityDomainRouterFactory.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
AbstractApplicationContext createApplicationContext(Domain domain) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.setParent(gatewayApplicationContext);
    context.setClassLoader(new ReactorHandlerClassLoader(gatewayApplicationContext.getClassLoader()));
    context.setEnvironment((ConfigurableEnvironment) gatewayApplicationContext.getEnvironment());

    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setIgnoreUnresolvablePlaceholders(true);
    configurer.setEnvironment(gatewayApplicationContext.getEnvironment());
    context.addBeanFactoryPostProcessor(configurer);

    context.getBeanFactory().registerSingleton("domain", domain);
    context.register(HandlerConfiguration.class);
    context.setId("context-domain-" + domain.getId());
    context.refresh();

    return context;
}
 
Example #2
Source File: ApplicationKeeper.java    From seata-samples with Apache License 2.0 6 votes vote down vote up
private void addShutdownHook(final AbstractApplicationContext applicationContext) {
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                applicationContext.close();
                LOGGER.info("ApplicationContext " + applicationContext + " is closed.");
            } catch (Exception e) {
                LOGGER.error("Failed to close ApplicationContext", e);
            }

            try {
                LOCK.lock();
                STOP.signal();
            } finally {
                LOCK.unlock();
            }
        }
    }));
}
 
Example #3
Source File: ContextHelper.java    From graphql-java-datetime with Apache License 2.0 6 votes vote down vote up
static public AbstractApplicationContext load() {
    AbstractApplicationContext context;

    try {
        context = AnnotationConfigApplicationContext.class.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    AnnotationConfigRegistry registry = (AnnotationConfigRegistry) context;

    registry.register(BaseConfiguration.class);
    registry.register(GraphQLJavaToolsAutoConfiguration.class);

    context.refresh();

    return context;
}
 
Example #4
Source File: PublicNetworkTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void globalTearDown() throws Exception {
    s_lockMaster.cleanupForServer(s_msId);
    JmxUtil.unregisterMBean("Locks", "Locks");
    s_lockMaster = null;

    AbstractApplicationContext ctx = (AbstractApplicationContext)ComponentContext.getApplicationContext();
    Map<String, ComponentLifecycle> lifecycleComponents = ctx.getBeansOfType(ComponentLifecycle.class);
    for (ComponentLifecycle bean : lifecycleComponents.values()) {
        bean.stop();
    }
    ctx.close();

    s_logger.info("destroying mysql server instance running at port <" + s_mysqlServerPort + ">");
    TestDbSetup.destroy(s_mysqlServerPort, null);
}
 
Example #5
Source File: RepositoryStartStopTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 *
 * Enable test after this issue is resolved: https://issues.alfresco.com/jira/browse/REPO-4176
 * @throws Exception
 */
public void ignoreTestFullContextRefresh() throws Exception
{

    assertNoCachedApplicationContext();

    // Open it, and use it
    ApplicationContext ctx = getFullContext();
    assertNotNull(ctx);
    doTestBasicWriteOperations(ctx);

    // Refresh it, shouldn't break anything
    ((AbstractApplicationContext)ctx).refresh();
    assertNotNull(ctx);
    doTestBasicWriteOperations(ctx);

    // And finally close it
    ApplicationContextHelper.closeApplicationContext();
    assertNoCachedApplicationContext();
}
 
Example #6
Source File: CustomizedMessageSourceBeanDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        ConfigurableApplicationContext applicationContext =
                // Primary Configuration Class
                new SpringApplicationBuilder(CustomizedMessageSourceBeanDemo.class)
                        .web(WebApplicationType.NONE)
                        .run(args);

        ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();

        if (beanFactory.containsBean(AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME)) {
            // 查找 MessageSource 的 BeanDefinition
            System.out.println(beanFactory.getBeanDefinition(AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME));
            // 查找 MessageSource Bean
            MessageSource messageSource = applicationContext.getBean(AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
            System.out.println(messageSource);
        }

        // 关闭应用上下文
        applicationContext.close();
    }
 
Example #7
Source File: EventNetstrapSpringRunListener.java    From netstrap with Apache License 2.0 6 votes vote down vote up
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
    FailedApplicationEvent event = new FailedApplicationEvent(this.application, context, exception);
    if (context != null && context.isActive()) {
        context.publishEvent(event);
    } else {
        if (context instanceof AbstractApplicationContext) {
            for (ApplicationListener<?> listener : ((AbstractApplicationContext) context)
                    .getApplicationListeners()) {
                this.initialMulticaster.addApplicationListener(listener);
            }
        }

        this.initialMulticaster.setErrorHandler(new LoggingErrorHandler());
        this.initialMulticaster.multicastEvent(event);
    }
}
 
Example #8
Source File: UserProducerApp.java    From Spring with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    AbstractApplicationContext context = new AnnotationConfigApplicationContext(
            ServiceConfig.class, JmsCommonConfig.class, JmsProducerConfig.class);
    UserService userService = context.getBean(UserService.class);
    UserSender userSender = context.getBean(UserSender.class);

    List<User> users = userService.findAll();

    assertTrue(users.size() > 0);
    for (User user : users) {
        userSender.sendMessage(user);
    }

    log.info("User message sent. Wait for confirmation...");

    System.in.read();

    context.close();
}
 
Example #9
Source File: ApplicationKeeper.java    From seata-samples with Apache License 2.0 6 votes vote down vote up
private void addShutdownHook(final AbstractApplicationContext applicationContext) {
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                applicationContext.close();
                LOGGER.info("ApplicationContext " + applicationContext + " is closed.");
            } catch (Exception e) {
                LOGGER.error("Failed to close ApplicationContext", e);
            }

            try {
                LOCK.lock();
                STOP.signal();
            } finally {
                LOCK.unlock();
            }
        }
    }));
}
 
Example #10
Source File: GatewayIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void listenersInOrder() {
	assertThat(context).isInstanceOf(AbstractApplicationContext.class);
	AbstractApplicationContext ctxt = (AbstractApplicationContext) context;
	List<ApplicationListener<?>> applicationListeners = new ArrayList<>(
			ctxt.getApplicationListeners());
	AnnotationAwareOrderComparator.sort(applicationListeners);
	int weightFilterIndex = applicationListeners
			.indexOf(context.getBean(WeightCalculatorWebFilter.class));
	int routeLocatorIndex = applicationListeners
			.indexOf(context.getBean(CachingRouteLocator.class));
	assertThat(weightFilterIndex > routeLocatorIndex)
			.as("CachingRouteLocator is after WeightCalculatorWebFilter").isTrue();
}
 
Example #11
Source File: CentipedeShell.java    From centipede with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
 AbstractApplicationContext createApplicationContext(CentipedeShellOptions centipedeOptions, List<String> contextPath) {
    contextPath.addAll(centipedeOptions.applicationContext);
    contextPath.addAll(centipedeOptions.applicationContext);

    if(centipedeOptions.eager && centipedeOptions.lazy)
        throw new MisconfigurationException("Cannot force eager and lazy load at same time");

    Boolean forcedMode =
            centipedeOptions.lazy ? Boolean.TRUE :
                    (centipedeOptions.eager ? Boolean.FALSE : isLazyByDefault());

    return (forcedMode==null) ? newContext(contextPath) :
            newContext(contextPath,forcedMode);
}
 
Example #12
Source File: AbstractTestNGCobarClientTest.java    From cobarclient with Apache License 2.0 5 votes vote down vote up
@AfterClass
public void cleanup() {
    if (applicationContext != null) {
        logger.info("shut down Application Context to clean up.");            
        ((AbstractApplicationContext) applicationContext).destroy();
    }
}
 
Example #13
Source File: AnnotationResource.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring/spring-annotation.xml");
	AnnotationResource annotationResource = (AnnotationResource) ctx.getBean("annotationResource");

	log.debug("type: {}, name: {}", annotationResource.getFieldA().getClass(),
		annotationResource.getFieldA().getName());

	log.debug("type: {}, name: {}", annotationResource.getFieldB().getClass(),
		annotationResource.getFieldB().getName());

	log.debug("type: {}, name: {}", annotationResource.getFieldC().getClass(),
		annotationResource.getFieldC().getName());

	ctx.close();
}
 
Example #14
Source File: FirstTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Override
protected AbstractApplicationContext createApplicationContext() {
    // create a Spring Java Config context which is named AnnotationConfigApplicationContext
    AnnotationConfigApplicationContext acc = new AnnotationConfigApplicationContext();
    // then we must register the @Configuration class
    acc.register(MyApplication.class);
    return acc;
}
 
Example #15
Source File: ScopesIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenSingletonScope_whenSetName_thenEqualNames() {
    final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");

    final Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
    final Person personSingletonB = (Person) applicationContext.getBean("personSingleton");

    personSingletonA.setName(NAME);
    Assert.assertEquals(NAME, personSingletonB.getName());

    ((AbstractApplicationContext) applicationContext).close();
}
 
Example #16
Source File: CentipedeShell.java    From centipede with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static AbstractApplicationContext newContext(List<String> applicationContextPath,boolean beLazy) {
    if(beLazy) {
        applicationContextPath.add("classpath:com/ontology2/centipede/shell/addLazinessAttributeToAllBeanDefinitions.xml");
    } else {
        applicationContextPath.add("classpath:com/ontology2/centipede/shell/addEagernessAttributeToAllBeanDefinitions.xml");
    }
    return new ClassPathXmlApplicationContext(applicationContextPath.toArray(new String[]{}));
}
 
Example #17
Source File: CseApplicationListener.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
  public void onApplicationEvent(ApplicationEvent event) {
    if (initEventClass.isInstance(event)) {
      if (applicationContext instanceof AbstractApplicationContext) {
        ((AbstractApplicationContext) applicationContext).registerShutdownHook();
      }

      SCBEngine scbEngine = SCBEngine.getInstance();
      //SCBEngine init first, hence we do not need worry that when other beans need use the
      //producer microserviceMeta, the SCBEngine is not inited.
//        String serviceName = RegistryUtils.getMicroservice().getServiceName();
//        SCBEngine.getInstance().setProducerMicroserviceMeta(new MicroserviceMeta(serviceName).setConsumer(false));
//        SCBEngine.getInstance().setProducerProviderManager(applicationContext.getBean(ProducerProviderManager.class));
//        SCBEngine.getInstance().setConsumerProviderManager(applicationContext.getBean(ConsumerProviderManager.class));
//        SCBEngine.getInstance().setTransportManager(applicationContext.getBean(TransportManager.class));
      scbEngine.setFilterChainsManager(applicationContext.getBean(FilterChainsManager.class));
      scbEngine.getConsumerProviderManager().getConsumerProviderList()
          .addAll(applicationContext.getBeansOfType(ConsumerProvider.class).values());
      scbEngine.getProducerProviderManager().getProducerProviderList()
          .addAll(applicationContext.getBeansOfType(ProducerProvider.class).values());
      scbEngine.addBootListeners(applicationContext.getBeansOfType(BootListener.class).values());

      scbEngine.run();
    } else if (event instanceof ContextClosedEvent) {
      if (SCBEngine.getInstance() != null) {
        SCBEngine.getInstance().destroy();
      }
    }
  }
 
Example #18
Source File: AbstractCosmosConfigurationIT.java    From spring-data-cosmosdb with MIT License 5 votes vote down vote up
@Test
public void containsCosmosDbFactory() {
    final AbstractApplicationContext context = new AnnotationConfigApplicationContext(
            TestCosmosConfiguration.class);

    Assertions.assertThat(context.getBean(CosmosDbFactory.class)).isNotNull();
}
 
Example #19
Source File: AbstractCosmosConfigurationIT.java    From spring-data-cosmosdb with MIT License 5 votes vote down vote up
@Test
public void objectMapperIsConfigurable() {
    final AbstractApplicationContext context = new AnnotationConfigApplicationContext(
            ObjectMapperConfiguration.class);

    Assertions.assertThat(context.getBean(ObjectMapper.class)).isNotNull();
    Assertions.assertThat(context.getBean(OBJECTMAPPER_BEAN_NAME)).isNotNull();
}
 
Example #20
Source File: PlainTextEmailSchedulingApplication.java    From spring-boot-email-tools with Apache License 2.0 5 votes vote down vote up
private void close() {
    TimerTask shutdownTask = new TimerTask() {
        @Override
        public void run() {
            ((AbstractApplicationContext) applicationContext).close();
        }
    };
    Timer shutdownTimer = new Timer();
    shutdownTimer.schedule(shutdownTask, TimeUnit.SECONDS.toMillis(20));
}
 
Example #21
Source File: QuartzSchedulerLifecycleTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test // SPR-6354
public void destroyLazyInitSchedulerWithCustomShutdownOrderDoesNotHang() {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("quartzSchedulerLifecycleTests.xml", this.getClass());
	assertNotNull(context.getBean("lazyInitSchedulerWithCustomShutdownOrder"));
	StopWatch sw = new StopWatch();
	sw.start("lazyScheduler");
	context.destroy();
	sw.stop();
	assertTrue("Quartz Scheduler with lazy-init is hanging on destruction: " +
			sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 500);
}
 
Example #22
Source File: EventPublisherAutoConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Server internal event publisher that allows parallel event processing if
 * the event listener is marked as so.
 *
 * @return publisher bean
 */
@Bean(name = AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
ApplicationEventMulticaster applicationEventMulticaster(@Qualifier("asyncExecutor") final Executor executor,
        final TenantAware tenantAware) {
    final SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = new TenantAwareApplicationEventPublisher(
            tenantAware, applicationEventFilter());
    simpleApplicationEventMulticaster.setTaskExecutor(executor);
    return simpleApplicationEventMulticaster;
}
 
Example #23
Source File: SpringNewExceptionTest.java    From camelinaction2 with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractApplicationContext createApplicationContext() {
    return new ClassPathXmlApplicationContext("camelinaction/SpringNewExceptionTest.xml");
}
 
Example #24
Source File: JmsTransactionEndpointSpringTest.java    From camel-cookbook-examples with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractApplicationContext createApplicationContext() {
    return new ClassPathXmlApplicationContext("META-INF/spring/jmsTransactionEndpoint-context.xml");
}
 
Example #25
Source File: QueueBridgeXBeanTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractApplicationContext createApplicationContext() {
   return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/queue-xbean.xml");
}
 
Example #26
Source File: OperationSpringTest.java    From camel-cookbook-examples with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractApplicationContext createApplicationContext() {
    System.setProperty("port1", String.valueOf(port1));

    return new ClassPathXmlApplicationContext("META-INF/spring/mutipleOperations-context.xml");
}
 
Example #27
Source File: MonitorSpringTest.java    From camel-cookbook-examples with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractApplicationContext createApplicationContext() {
    return new ClassPathXmlApplicationContext("META-INF/spring/monitor-context.xml");
}
 
Example #28
Source File: XACommitTest.java    From camelinaction2 with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractApplicationContext createApplicationContext() {
    return new ClassPathXmlApplicationContext("spring-context.xml");
}
 
Example #29
Source File: SpringOrderServiceTest.java    From camelinaction2 with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractApplicationContext createApplicationContext() {
    return new ClassPathXmlApplicationContext("camelinaction/SpringOrderServiceTest.xml");
}
 
Example #30
Source File: JmsTransactionRequestReplySpringTest.java    From camel-cookbook-examples with Apache License 2.0 4 votes vote down vote up
@Override
protected AbstractApplicationContext createApplicationContext() {
    return new ClassPathXmlApplicationContext("META-INF/spring/jmsTransactionRequestReply-context.xml");
}