类org.springframework.context.support.AbstractApplicationContext源码实例Demo

下面列出了怎么用org.springframework.context.support.AbstractApplicationContext的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: seata-samples   文件: ApplicationKeeper.java
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();
            }
        }
    }));
}
 
源代码2 项目: seata-samples   文件: ApplicationKeeper.java
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();
            }
        }
    }));
}
 
源代码3 项目: cloudstack   文件: PublicNetworkTest.java
@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);
}
 
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();
    }
 
源代码5 项目: Spring   文件: UserProducerApp.java
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();
}
 
源代码6 项目: netstrap   文件: EventNetstrapSpringRunListener.java
@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);
    }
}
 
/**
 *
 * 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();
}
 
源代码8 项目: graphql-java-datetime   文件: ContextHelper.java
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;
}
 
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;
}
 
源代码10 项目: hawkbit   文件: EventPublisherAutoConfiguration.java
/**
 * 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;
}
 
源代码11 项目: centipede   文件: CentipedeShell.java
@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);
}
 
@AfterClass
public void cleanup() {
    if (applicationContext != null) {
        logger.info("shut down Application Context to clean up.");            
        ((AbstractApplicationContext) applicationContext).destroy();
    }
}
 
源代码13 项目: spring-tutorial   文件: AnnotationResource.java
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();
}
 
源代码14 项目: camelinaction2   文件: FirstTest.java
@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;
}
 
源代码15 项目: tutorials   文件: ScopesIntegrationTest.java
@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();
}
 
源代码16 项目: centipede   文件: CentipedeShell.java
@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[]{}));
}
 
@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();
      }
    }
  }
 
@Test
public void containsCosmosDbFactory() {
    final AbstractApplicationContext context = new AnnotationConfigApplicationContext(
            TestCosmosConfiguration.class);

    Assertions.assertThat(context.getBean(CosmosDbFactory.class)).isNotNull();
}
 
@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();
}
 
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));
}
 
@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);
}
 
@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();
}
 
源代码23 项目: java-client   文件: DefaultAspect.java
DefaultAspect(AbstractApplicationContext context, WebDriver driver) {
    this.context = context;
    this.driver = driver;
}
 
@Override
protected AbstractApplicationContext createApplicationContext() {
    System.setProperty("port1", String.valueOf(port1));

    return new ClassPathXmlApplicationContext("META-INF/spring/api-context.xml");
}
 
@Override
protected AbstractApplicationContext createApplicationContext() {
    return new ClassPathXmlApplicationContext("META-INF/spring/logthroughput-context.xml");
}
 
@Override
protected AbstractApplicationContext createApplicationContext() {
    return new ClassPathXmlApplicationContext("META-INF/spring/recipientList-unrecognized-context.xml");
}
 
源代码27 项目: activemq-artemis   文件: QueueBridgeXBeanTest.java
@Override
protected AbstractApplicationContext createApplicationContext() {
   return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/queue-xbean.xml");
}
 
源代码28 项目: camel-cookbook-examples   文件: DirectSpringTest.java
@Override
protected AbstractApplicationContext createApplicationContext() {
    return new ClassPathXmlApplicationContext("META-INF/spring/direct-context.xml");
}
 
源代码29 项目: AvatarMQ   文件: AvatarMQContext.java
public AbstractApplicationContext get() {
    return applicationContext;
}
 
@Override
protected AbstractApplicationContext createApplicationContext() {
    return new ClassPathXmlApplicationContext("META-INF/spring/jmsTransaction-context.xml");
}
 
 同包方法