Java 类org.springframework.context.ConfigurableApplicationContext 实例源码

项目:spring_integration_examples    文件:Application.java   
@SuppressWarnings("unchecked")
public static void main (String[] args){

    ConfigurableApplicationContext ac =
            new ClassPathXmlApplicationContext("/context.xml");
    PollableChannel feedChannel = ac.getBean("feedChannel", PollableChannel.class);

    for (int i = 0; i < 10; i++) {
        Message<SyndEntry> message = (Message<SyndEntry>) feedChannel.receive(1000);
        if (message != null){
            System.out.println("==========="+i+"===========");
            SyndEntry entry = message.getPayload();
            System.out.println(entry.getAuthor());
            System.out.println(entry.getPublishedDate());
            System.out.println(entry.getTitle());
            System.out.println(entry.getUri());
            System.out.println(entry.getLink());
            System.out.println("======================");

        }
    }
    ac.close();


}
项目:gauravbytes    文件:App.java   
public static void main(String[] args) {
    try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);) {
        Dictionary singletonDictionary = context.getBean("singletonDictionary", Dictionary.class);
        logger.info("Singleton Scope example starts");
        singletonDictionary.addWord("Give");
        singletonDictionary.addWord("Take");
        int totalWords = singletonDictionary.totalWords();
        logger.info("Need to have two words. Total words are : " + totalWords);
        logger.info(singletonDictionary.toString());
        singletonDictionary = context.getBean("singletonDictionary", Dictionary.class);
        logger.info("Need to have two words. Total words are : " + totalWords);
        logger.info(singletonDictionary.toString());
        logger.info("Singleton Scope example ends");

        Dictionary prototypeDictionary = context.getBean("prototypeDictionary", Dictionary.class);
        logger.info("Prototype scope example starts");
        prototypeDictionary.addWord("Give 2");
        prototypeDictionary.addWord("Take 2");
        logger.info("Need to have two words. Total words are: " + prototypeDictionary.totalWords());
        logger.info(prototypeDictionary.toString());
        prototypeDictionary = context.getBean("prototypeDictionary", Dictionary.class);
        logger.info("zero word count. Total words are: " + prototypeDictionary.totalWords());
        logger.info(prototypeDictionary.toString());
    }
}
项目:lams    文件:DelegatingFilterProxy.java   
/**
 * Return the {@code WebApplicationContext} passed in at construction time, if available.
 * Otherwise, attempt to retrieve a {@code WebApplicationContext} from the
 * {@code ServletContext} attribute with the {@linkplain #setContextAttribute
 * configured name} if set. Otherwise look up a {@code WebApplicationContext} under
 * the well-known "root" application context attribute. The
 * {@code WebApplicationContext} must have already been loaded and stored in the
 * {@code ServletContext} before this filter gets initialized (or invoked).
 * <p>Subclasses may override this method to provide a different
 * {@code WebApplicationContext} retrieval strategy.
 * @return the {@code WebApplicationContext} for this proxy, or {@code null} if not found
 * @see #DelegatingFilterProxy(String, WebApplicationContext)
 * @see #getContextAttribute()
 * @see WebApplicationContextUtils#getWebApplicationContext(javax.servlet.ServletContext)
 * @see WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
 */
protected WebApplicationContext findWebApplicationContext() {
    if (this.webApplicationContext != null) {
        // the user has injected a context at construction time -> use it
        if (this.webApplicationContext instanceof ConfigurableApplicationContext) {
            if (!((ConfigurableApplicationContext)this.webApplicationContext).isActive()) {
                // the context has not yet been refreshed -> do so before returning it
                ((ConfigurableApplicationContext)this.webApplicationContext).refresh();
            }
        }
        return this.webApplicationContext;
    }
    String attrName = getContextAttribute();
    if (attrName != null) {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);
    }
    else {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }
}
项目:configx    文件:ConfigPropertyResolver.java   
@Override
public void afterPropertiesSet() throws Exception {
    if (this.propertySources == null) {
        this.propertySources = deducePropertySources();
    }

    if (this.conversionService == null) {
        this.conversionService = getOptionalBean(
                ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME,
                ConfigurableConversionService.class);
    }

    // If no explicit conversion service is provided we add one so that (at least)
    // comma-separated arrays of convertibles can be bound automatically
    if (this.conversionService == null) {
        this.conversionService = getDefaultConversionService();
    }

    this.propertyResolver = new PropertySourcesPropertyResolver(this.propertySources);
    this.propertyResolver.setConversionService(this.conversionService);
}
项目:lams    文件:LoadTimeWeaverAwareProcessor.java   
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof LoadTimeWeaverAware) {
        LoadTimeWeaver ltw = this.loadTimeWeaver;
        if (ltw == null) {
            Assert.state(this.beanFactory != null,
                    "BeanFactory required if no LoadTimeWeaver explicitly specified");
            ltw = this.beanFactory.getBean(
                    ConfigurableApplicationContext.LOAD_TIME_WEAVER_BEAN_NAME, LoadTimeWeaver.class);
        }
        ((LoadTimeWeaverAware) bean).setLoadTimeWeaver(ltw);
    }
    return bean;
}
项目:SkyEye    文件:Launcher.java   
public static void main(String[] args) {
    SpringApplicationBuilder builder = new SpringApplicationBuilder(Launcher.class);
    Set<ApplicationListener<?>> listeners = builder.application().getListeners();
    for (Iterator<ApplicationListener<?>> it = listeners.iterator(); it.hasNext();) {
        ApplicationListener<?> listener = it.next();
        if (listener instanceof LoggingApplicationListener) {
            it.remove();
        }
    }
    builder.application().setListeners(listeners);
    ConfigurableApplicationContext context = builder.run(args);
    LOGGER.info("collector metrics start successfully");

    KafkaConsumer kafkaConsumer = (KafkaConsumer<byte[], String>) context.getBean("kafkaConsumer");
    Task task = (Task) context.getBean("metricsTask");

    // 优雅停止项目
    Runtime.getRuntime().addShutdownHook(new ShutdownHookRunner(kafkaConsumer, task));
    task.doTask();
}
项目:gemini.blueprint    文件:AbstractSingleSpringContextTests.java   
/**
 * Return the ApplicationContext that this base class manages; may be
 * {@code null}.
 */
public final ConfigurableApplicationContext getApplicationContext() {
    // lazy load, in case setUp() has not yet been called.
    if (this.applicationContext == null) {
        try {
            this.applicationContext = getContext(contextKey());
        }
        catch (Exception e) {
            // log and continue...
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Caught exception while retrieving the ApplicationContext for test [" +
                        getClass().getName() + "." + getName() + "].", e);
            }
        }
    }

    return this.applicationContext;
}
项目:aem-orchestrator    文件:AemOrchestrator.java   
public static void main(String[] args) throws Exception {
    ConfigurableApplicationContext context = SpringApplication.run(AemOrchestrator.class, args);

    //Need to wait for Author ELB is be in a healthy state before reading messages from the SQS queue
    ResourceReadyChecker resourceReadyChecker = context.getBean(ResourceReadyChecker.class);

    boolean isStartupOk = false;

    if(resourceReadyChecker.isResourcesReady()) {
        OrchestratorMessageListener messageReceiver = context.getBean(OrchestratorMessageListener.class);

        try {
            messageReceiver.start();
            isStartupOk = true;
        } catch (Exception e) {
            logger.error("Failed to start message receiver", e);
        }
    }

    if(isStartupOk) {
        logger.info("AEM Orchestrator started");
    } else {
        logger.info("Failed to start AEM Orchestrator");
        context.close(); //Exit the application
    }
}
项目:wamp2spring    文件:HandlerMethodService.java   
public HandlerMethodService(ConversionService conversionService,
        List<HandlerMethodArgumentResolver> customArgumentResolvers,
        ObjectMapper objectMapper, ApplicationContext applicationContext) {
    this.conversionService = conversionService;
    this.parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    this.argumentResolvers = new HandlerMethodArgumentResolverComposite();

    ConfigurableBeanFactory beanFactory = ClassUtils.isAssignableValue(
            ConfigurableApplicationContext.class, applicationContext)
                    ? ((ConfigurableApplicationContext) applicationContext)
                            .getBeanFactory()
                    : null;

    this.argumentResolvers.addResolver(
            new HeaderMethodArgumentResolver(this.conversionService, beanFactory));
    this.argumentResolvers.addResolver(new HeadersMethodArgumentResolver());
    this.argumentResolvers.addResolver(new WampMessageMethodArgumentResolver());
    this.argumentResolvers.addResolver(new PrincipalMethodArgumentResolver());
    this.argumentResolvers.addResolver(new WampSessionIdMethodArgumentResolver());
    this.argumentResolvers.addResolvers(customArgumentResolvers);

    this.objectMapper = objectMapper;
}
项目:k-framework    文件:KApplication.java   
public void run(Class clazz, String[] args) {
        SpringApplication springApplication = new SpringApplication(clazz);
//        springApplication.addListeners(new ApplicationPidFileWriter("application.pid"));
        ConfigurableApplicationContext ctx = springApplication.run(args);
        Environment env = ctx.getEnvironment();
        if (env.acceptsProfiles(ProfileConstant.RT_SCRIPT)) {
            if (args.length > 0) {
                String shellClass = args[0];
                ScriptInterface script = (ScriptInterface) ctx.getBean(shellClass);
                if (null != script) {
                    try {
                        if (args.length > 1) {
                            script.run(Arrays.copyOfRange(args, 1, args.length));
                        } else {
                            script.run(new String[]{});
                        }
                    } catch (Exception e) {
                        scriptLogger.error("error occur", e);
                    }
                }
            }
        }
    }
项目:state-channels    文件:ChannelNodeApplication.java   
public static void main(String[] args) throws InterruptedException {
    log.info("Initializing channel node");
    ConfigurableApplicationContext context = SpringApplication.run(ChannelNodeApplication.class, args);
    log.info("Starting API interfaces");
    context.start();
    NodeServer nodeServer = context.getBean(NodeServer.class);
    log.info("Channel node started");
    nodeServer.awaitTermination();
}
项目:SkyEye    文件:Launcher.java   
public static void main(String[] args) {
    SpringApplicationBuilder builder = new SpringApplicationBuilder(Launcher.class);
    Set<ApplicationListener<?>> listeners = builder.application().getListeners();
    for (Iterator<ApplicationListener<?>> it = listeners.iterator(); it.hasNext();) {
        ApplicationListener<?> listener = it.next();
        if (listener instanceof LoggingApplicationListener) {
            it.remove();
        }
    }
    builder.application().setListeners(listeners);
    ConfigurableApplicationContext context = builder.run(args);
    LOGGER.info("collector indexer start successfully");

    KafkaConsumer kafkaConsumer = (KafkaConsumer<byte[], String>) context.getBean("kafkaConsumer");
    Task task = (Task) context.getBean("indexerTask");

    // 优雅停止项目
    Runtime.getRuntime().addShutdownHook(new ShutdownHookRunner(kafkaConsumer, task));
    task.doTask();
}
项目:embedded-database-spring-test    文件:EmbeddedPostgresContextCustomizerFactory.java   
@Override
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
    Class<?> testClass = mergedConfig.getTestClass();
    FlywayTest flywayAnnotation = AnnotatedElementUtils.findMergedAnnotation(testClass, FlywayTest.class);

    BeanDefinitionRegistry registry = getBeanDefinitionRegistry(context);
    RootBeanDefinition registrarDefinition = new RootBeanDefinition();

    registrarDefinition.setBeanClass(PreloadableEmbeddedPostgresRegistrar.class);
    registrarDefinition.getConstructorArgumentValues()
            .addIndexedArgumentValue(0, databaseAnnotation);
    registrarDefinition.getConstructorArgumentValues()
            .addIndexedArgumentValue(1, flywayAnnotation);

    registry.registerBeanDefinition("preloadableEmbeddedPostgresRegistrar", registrarDefinition);
}
项目:smarti    文件:Application.java   
public static void main(String[] args) {
    final SpringApplication app = new SpringApplication(Application.class);
    // save the pid into a file...
    app.addListeners(new ApplicationPidFileWriter("smarti.pid"));

    final ConfigurableApplicationContext context = app.run(args);
    final ConfigurableEnvironment env = context.getEnvironment();

    try {
        //http://localhost:8080/admin/index.html
        final URI uri = new URI(
                (env.getProperty("server.ssl.enabled", Boolean.class, false) ? "https" : "http"),
                null,
                (env.getProperty("server.address", "localhost")),
                (env.getProperty("server.port", Integer.class, 8080)),
                (env.getProperty("server.context-path", "/")).replaceAll("//+", "/"),
                null, null);

        log.info("{} started: {}",
                env.getProperty("server.display-name", context.getDisplayName()),
                uri);
    } catch (URISyntaxException e) {
        log.warn("Could not build launch-url: {}", e.getMessage());
    }
}
项目:jkami    文件:MapperScannerConfigurer.java   
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    /**
     * 注册通用Dao
     */
    registerBaseCommonDao(registry);
    /**
     * 注册代理类
     */
    registerProxyHandler(registry);
    /**
     * 加载其他层接口
     */
    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry, annotation);
    scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
项目:spring-seed    文件:ProfileApplicationContextInitializer.java   
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    this.environment = applicationContext.getEnvironment();
    this.resourceLoader = applicationContext;
    this.profile = Profiles.getActiveProfile(environment);

    NameLocationPair pair = getPropertySourceFirst();
    if(pair != null){
        addPropertySource(pair.getName(),pair.getLocation());
    }
    addPropertySource(OVERRIDE_PROPERTIES_SOURCE_NAME, System.getProperty(OVERRIDE_PROPERTIES_SOURCE_LOCATION));
    addPropertySource(PROJECT_PROPERTIES_SOURCE_NAME, PROJECT_PROPERTIES_SOURCE_LOCATION);
    addPropertySource(PROJECT_PROPERTIES_SOURCE_DEFAULT_NAME, PROJECT_PROPERTIES_SOURCE_DEFAULT_LOCATION);
    addPropertySource(PARENT_PROPERTIES_SOURCE_NAME, PARENT_PROPERTIES_SOURCE_LOCATION);
    addPropertySource(PARENT_PROPERTIES_SOURCE_DEFAULT_NAME, PARENT_PROPERTIES_SOURCE_DEFAULT_LOCATION);

    LogbackConfig.init(LOGBACK_CONFIG_LOCATION);
}
项目:export-distro    文件:Application.java   
public static void main(String[] args) {
    ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
    String welcomeMsg = ctx.getEnvironment().getProperty("app.open.msg");
    ZeroMQEventSubscriber sub = ctx.getBean(ZeroMQEventSubscriber.class);
    System.out.println(welcomeMsg);
    sub.receive();
}
项目:lams    文件:ContextLoader.java   
@SuppressWarnings("unchecked")
private Class<ApplicationContextInitializer<ConfigurableApplicationContext>> loadInitializerClass(String className) {
    try {
        Class<?> clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader());
        Assert.isAssignable(ApplicationContextInitializer.class, clazz);
        return (Class<ApplicationContextInitializer<ConfigurableApplicationContext>>) clazz;
    }
    catch (ClassNotFoundException ex) {
        throw new ApplicationContextException("Failed to load context initializer class [" + className + "]", ex);
    }
}
项目:cassandra-it    文件:CounterIntegrationTestContainers.java   
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
    EnvironmentTestUtils.addEnvironment("testcontainers", configurableApplicationContext.getEnvironment(),
            "cassandra.host=" + cassandra.getContainerIpAddress(),
            "cassandra.port=" + cassandra.getMappedPort(9042)
    );
}
项目:lams    文件:ServletContextLiveBeansView.java   
@Override
protected Set<ConfigurableApplicationContext> findApplicationContexts() {
    Set<ConfigurableApplicationContext> contexts = new LinkedHashSet<ConfigurableApplicationContext>();
    Enumeration<String> attrNames = this.servletContext.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        String attrName = attrNames.nextElement();
        Object attrValue = this.servletContext.getAttribute(attrName);
        if (attrValue instanceof ConfigurableApplicationContext) {
            contexts.add((ConfigurableApplicationContext) attrValue);
        }
    }
    return contexts;
}
项目:miscroServiceHello    文件:App.java   
public static void main(String[] args) {
    SpringApplication bootstrap = new  SpringApplication(SpringBootRunner.class);

    bootstrap.addListeners(new MyStartListner());
    //  对Context进行最后的设置工作
    bootstrap.addInitializers(new MyContextInitializer());
    //  增加命令

    ConfigurableApplicationContext context = bootstrap.run(args);

    //  触发一个事件
    MyTellEvent event = new MyTellEvent(context, "测试的事件信息");
    context.publishEvent(event);
}
项目:cas-5.1.0    文件:EnvironmentConversionServiceInitializer.java   
@Override
public void initialize(final ConfigurableApplicationContext ctx) {
    final DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(true);
    conversionService.setEmbeddedValueResolver(new CasConfigurationEmbeddedValueResolver(ctx));
    ctx.getEnvironment().setConversionService(conversionService);

}
项目:RestyPass    文件:RequestMappingProcessor.java   
private String resolve(String value) {
    if (StringUtils.hasText(value)
            && this.resourceLoader instanceof ConfigurableApplicationContext) {
        return ((ConfigurableApplicationContext) this.resourceLoader).getEnvironment()
                .resolvePlaceholders(value);
    }
    return value;
}
项目:tensorflow-spring-cloud-stream-app-starters    文件:TensorflowProcessorTestConfiguration.java   
@Bean
public BinderTestPropertiesInitializer loadProps(ConfigurableApplicationContext context) {
    // minimal properties for the context to load
    Properties properties = new Properties();
    properties.put("modelLocation", "classpath:tensorflow/model/linear_regression_graph.proto");
    properties.put("outputName", "add");
    return new BinderTestPropertiesInitializer(context, properties);
}
项目:springboot-graceful-shutdown    文件:GracefulShutdownHookTest.java   
@Before
public void setup() {
    // Prepare
    appContext = Mockito.mock(ConfigurableApplicationContext.class);
    confEnv = Mockito.mock(ConfigurableEnvironment.class);
    healthCheck = new GracefulShutdownHealthCheck();
    final HashMap<String, IProbeController> beans = new HashMap<>();
    beans.put(GracefulShutdownHealthCheck.class.getName(), healthCheck);

    // Test
    when(confEnv.getProperty(GracefulShutdownHook.GRACEFUL_SHUTDOWN_WAIT_SECONDS, "20")).thenReturn(String.valueOf(SHUTDOWN_WAIT_S));
    when(appContext.getEnvironment()).thenReturn(confEnv);
    when(appContext.getBeansOfType(IProbeController.class)).thenReturn(beans);
}
项目:gemini.blueprint    文件:NonOSGiLoaderProxyTest.java   
public void testProxy() throws Exception {
    // publish service
    bundleContext.registerService(new String[] { DataSource.class.getName(), Comparator.class.getName(),
        InitializingBean.class.getName(), Constants.class.getName() }, new Service(), new Hashtable());

    ConfigurableApplicationContext ctx = getNestedContext();
    assertNotNull(ctx);
    Object proxy = ctx.getBean("service");
    assertNotNull(proxy);
    assertTrue(proxy instanceof DataSource);
    assertTrue(proxy instanceof Comparator);
    assertTrue(proxy instanceof Constants);
    assertTrue(proxy instanceof InitializingBean);
    ctx.close();
}
项目:gemini.blueprint    文件:ClassUtilsTest.java   
public void testInterfacesHierarchy() {
       //Closeable.class,
    Class<?>[] clazz = ClassUtils.getAllInterfaces(DelegatedExecutionOsgiBundleApplicationContext.class);
    Class<?>[] expected =
            { ConfigurableOsgiBundleApplicationContext.class, ConfigurableApplicationContext.class,
                    ApplicationContext.class, Lifecycle.class, Closeable.class, EnvironmentCapable.class, ListableBeanFactory.class,
                    HierarchicalBeanFactory.class, MessageSource.class, ApplicationEventPublisher.class,
                    ResourcePatternResolver.class, BeanFactory.class, ResourceLoader.class, AutoCloseable.class };

    assertTrue(compareArrays(expected, clazz));
}
项目:JRediClients    文件:SpringNamespaceWikiTest.java   
@Test
public void testReplicated() throws Exception {
    RedisRunner.RedisProcess master = new RedisRunner()
            .requirepass("do_not_use_if_it_is_not_set")
            .nosave()
            .randomDir()
            .run();
    RedisRunner.RedisProcess slave1 = new RedisRunner()
            .requirepass("do_not_use_if_it_is_not_set")
            .masterauth("do_not_use_if_it_is_not_set")
            .port(6380)
            .nosave()
            .randomDir()
            .slaveof("127.0.0.1", 6379)
            .run();
    RedisRunner.RedisProcess slave2 = new RedisRunner()
            .requirepass("do_not_use_if_it_is_not_set")
            .masterauth("do_not_use_if_it_is_not_set")
            .port(6381)
            .nosave()
            .randomDir()
            .slaveof("127.0.0.1", 6379)
            .run();
    try {
        ((ConfigurableApplicationContext)
                new ClassPathXmlApplicationContext("classpath:org/redisson/spring/support/namespace_wiki_replicated.xml"))
                .close();
    } finally {
        master.stop();
        slave1.stop();
        slave2.stop();
    }
}
项目:JRediClients    文件:SpringNamespaceWikiTest.java   
@Test
public void testCluster() throws Exception {
    ClusterRunner clusterRunner = new ClusterRunner()
            .addNode(new RedisRunner()
                    .requirepass("do_not_use_if_it_is_not_set")
                    .port(6379)
                    .randomDir()
                    .nosave())
            .addNode(new RedisRunner()
                    .requirepass("do_not_use_if_it_is_not_set")
                    .port(6380)
                    .randomDir()
                    .nosave())
            .addNode(new RedisRunner()
                    .requirepass("do_not_use_if_it_is_not_set")
                    .port(6381)
                    .randomDir()
                    .nosave());
    ClusterRunner.ClusterProcesses cluster = clusterRunner.run();

    try {
        ((ConfigurableApplicationContext)
                new ClassPathXmlApplicationContext("classpath:org/redisson/spring/support/namespace_wiki_cluster.xml"))
                .close();
    } finally {
        cluster.shutdown();
    }
}
项目:alfresco-data-model    文件:WebApplicationContextLoader.java   
public synchronized static ConfigurableApplicationContext getApplicationContext(ServletContext servletContext, final String[] configLocations,
        final String[] classLocations) throws IOException
{
    final AbstractApplicationContext ctx = (AbstractApplicationContext)BaseApplicationContextHelper.getApplicationContext(configLocations, classLocations);
    DefaultListableBeanFactory dlbf = new DefaultListableBeanFactory(ctx.getBeanFactory());
    GenericWebApplicationContext gwac = new GenericWebApplicationContext(dlbf);
    CmisServiceFactory factory = (CmisServiceFactory)ctx.getBean("CMISServiceFactory");

    servletContext.setAttribute(GenericWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, gwac);
       servletContext.setAttribute(CmisRepositoryContextListener.SERVICES_FACTORY, factory);
    gwac.setServletContext(servletContext);
    gwac.refresh();

    return gwac;
}
项目:gemini.blueprint    文件:ScopingTest.java   
private ConfigurableApplicationContext getAppCtx(String symBundle) {
    ServiceReference ref = OsgiServiceReferenceUtils.getServiceReference(bundleContext, "("
            + ConfigurableOsgiBundleApplicationContext.APPLICATION_CONTEXT_SERVICE_PROPERTY_NAME + "=" + symBundle
            + ")");

    if (ref == null)
        throw new IllegalArgumentException("cannot find appCtx for bundle " + symBundle);
    return (ConfigurableApplicationContext) bundleContext.getService(ref);
}
项目:scrumtracker2017    文件:Application.java   
public static void main(String[] args)
{
    ConfigurableApplicationContext context = new AnnotationConfigApplicationContext("hei2017.config");


    /*
    SprintService sprintService = context.getBean(SprintService.class);
    Sprint sprintTest = new Sprint();
    sprintTest.setNom("test sprint");
    sprintService.saveSprint(sprintTest);
     */
    context.close();
}
项目:lams    文件:LiveBeansView.java   
/**
 * Generate a JSON snapshot of current beans and their dependencies,
 * finding all active ApplicationContexts through {@link #findApplicationContexts()},
 * then delegating to {@link #generateJson(java.util.Set)}.
 */
@Override
public String getSnapshotAsJson() {
    Set<ConfigurableApplicationContext> contexts;
    if (this.applicationContext != null) {
        contexts = Collections.singleton(this.applicationContext);
    }
    else {
        contexts = findApplicationContexts();
    }
    return generateJson(contexts);
}
项目:gemini.blueprint    文件:AbstractOptionalDependencyInjectionTests.java   
/**
 * {@inheritDoc}
 * 
 * <p/>This implementation will create an empty bundle context in case no
 * locations are specified.
 */
protected ConfigurableApplicationContext createApplicationContext(String[] locations) {

    ConfigurableOsgiBundleApplicationContext context = null;

    if (ObjectUtils.isEmpty(locations)) {
        context = new EmptyOsgiApplicationContext();
       } else {
        context = new OsgiBundleXmlApplicationContext(locations);
       }

    context.setBundleContext(bundleContext);
    context.refresh();
    return context;
}
项目:lams    文件:ComponentScanBeanDefinitionParser.java   
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    String[] basePackages = StringUtils.tokenizeToStringArray(element.getAttribute(BASE_PACKAGE_ATTRIBUTE),
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

    // Actually scan for bean definitions and register them.
    ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
    Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
    registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

    return null;
}
项目:alfresco-repository    文件:RenditionServiceIntegrationTest.java   
/**
 * Loads this executor into the ApplicationContext, if it
 *  isn't already there
 */
public static void registerIfNeeded(ConfigurableApplicationContext ctx)
{
   if(!ctx.containsBean(ENGINE_NAME))
   {
      // Create, and do dependencies
      DummyHelloWorldRenditionEngine hw = new DummyHelloWorldRenditionEngine();
      hw.setRuntimeActionService(
            (RuntimeActionService)ctx.getBean("actionService")
      );
      hw.setNodeService(
            (NodeService)ctx.getBean("NodeService")
      );
      hw.setContentService(
            (ContentService)ctx.getBean("ContentService")
      );
      hw.setRenditionService(
            (RenditionService)ctx.getBean("RenditionService")
      );
      hw.setBehaviourFilter(
            (BehaviourFilter)ctx.getBean("policyBehaviourFilter")
      );
      hw.setRenditionLocationResolver(
            (RenditionLocationResolver)ctx.getBean("renditionLocationResolver")
      );

      // Register
      ctx.getBeanFactory().registerSingleton(
            ENGINE_NAME, hw
      );
      hw.init();
   }
}
项目:lams    文件:ContextSingletonBeanFactoryLocator.java   
/**
 * Overrides the default method to refresh the ApplicationContext, invoking
 * {@link ConfigurableApplicationContext#refresh ConfigurableApplicationContext.refresh()}.
 */
@Override
protected void initializeDefinition(BeanFactory groupDef) {
    if (groupDef instanceof ConfigurableApplicationContext) {
        ((ConfigurableApplicationContext) groupDef).refresh();
    }
}
项目:micrometer    文件:SpringIntegrationApplication.java   
public static void main(String[] args) throws InterruptedException {
    ConfigurableApplicationContext ctx = SpringApplication.run(SpringIntegrationApplication.class, args);
    TempConverter converter = ctx.getBean(TempConverter.class);

    for (int i = 0; i < 1000; i++) {
        System.out.println(converter.fahrenheitToCelcius(68.0f));
        Thread.sleep(10);
    }

    ctx.close();
}
项目:lams    文件:ConditionEvaluator.java   
private ConfigurableListableBeanFactory deduceBeanFactory(BeanDefinitionRegistry source) {
    if (source instanceof ConfigurableListableBeanFactory) {
        return (ConfigurableListableBeanFactory) source;
    }
    if (source instanceof ConfigurableApplicationContext) {
        return (((ConfigurableApplicationContext) source).getBeanFactory());
    }
    return null;
}
项目:lams    文件:SpringContextResourceAdapter.java   
/**
 * Build a Spring ApplicationContext for the given JCA BootstrapContext.
 * <p>The default implementation builds a {@link ResourceAdapterApplicationContext}
 * and delegates to {@link #loadBeanDefinitions} for actually parsing the
 * specified configuration files.
 * @param bootstrapContext this ResourceAdapter's BootstrapContext
 * @return the Spring ApplicationContext instance
 */
protected ConfigurableApplicationContext createApplicationContext(BootstrapContext bootstrapContext) {
    ResourceAdapterApplicationContext applicationContext =
            new ResourceAdapterApplicationContext(bootstrapContext);
    // Set ResourceAdapter's ClassLoader as bean class loader.
    applicationContext.setClassLoader(getClass().getClassLoader());
    // Extract individual config locations.
    String[] configLocations =
            StringUtils.tokenizeToStringArray(getContextConfigLocation(), CONFIG_LOCATION_DELIMITERS);
    if (configLocations != null) {
        loadBeanDefinitions(applicationContext, configLocations);
    }
    applicationContext.refresh();
    return applicationContext;
}