public void init() { //启动并设置Spring AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class); ctx.registerShutdownHook(); NContext.setApplicationContext(ctx); //初始化房间管理器 HomeManager homeManager = HomeManager.getInstance(); homeManager.init(); //初始化用户管理器 PlayerManager playerManager = PlayerManager.getInstance(); playerManager.init(); //初始化Gateway ClientManager clientManager = ClientManager.getInstance(); clientManager.init(); //启动异步处理器 AsyncProcessor asyncProcessor = AsyncProcessor.getInstance(); asyncProcessor.start(); //启动滴答服务 TickerService tickerService = TickerService.getInstance(); tickerService.start(); }
/** * 配置基于配置的MessageSource */ private void configureMessageSource() { // MessageSource bean name String messageSourceBeanName = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME; // Config MessageSource bean name String configMessageSourceBeanName = CONFIG_MESSAGE_SOURCE_BEAN_NAME; // 基于配置服务的MessageSource ConfigMessageSource configMessageSource = beanFactory.getBean(configMessageSourceBeanName, ConfigMessageSource.class); // 如果已经存在MessageSource bean,则将ConfigMessageSource设置为messageSource的parent,将messageSource原来的parent设置为ConfigMessageSource的parent if (beanFactory.containsLocalBean(messageSourceBeanName)) { MessageSource messageSource = beanFactory.getBean(messageSourceBeanName, MessageSource.class); if (messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) messageSource; MessageSource pms = hms.getParentMessageSource(); hms.setParentMessageSource(configMessageSource); configMessageSource.setParentMessageSource(pms); } } else { beanFactory.registerSingleton(messageSourceBeanName, configMessageSource); } }
public void testAppContextClassHierarchy() { Class<?>[] clazz = ClassUtils.getClassHierarchy(OsgiBundleXmlApplicationContext.class, ClassUtils.ClassSet.ALL_CLASSES); //Closeable.class, Class<?>[] expected = new Class<?>[] { OsgiBundleXmlApplicationContext.class, AbstractDelegatedExecutionApplicationContext.class, AbstractOsgiBundleApplicationContext.class, AbstractRefreshableApplicationContext.class, AbstractApplicationContext.class, DefaultResourceLoader.class, ResourceLoader.class, AutoCloseable.class, DelegatedExecutionOsgiBundleApplicationContext.class, ConfigurableOsgiBundleApplicationContext.class, ConfigurableApplicationContext.class, ApplicationContext.class, Lifecycle.class, Closeable.class, EnvironmentCapable.class, ListableBeanFactory.class, HierarchicalBeanFactory.class, ApplicationEventPublisher.class, ResourcePatternResolver.class, MessageSource.class, BeanFactory.class, DisposableBean.class }; assertTrue(compareArrays(expected, clazz)); }
public static void main (String [] args) { @SuppressWarnings({ "resource"}) AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); PumpEngine engine = (PumpEngine)context.getBean(PumpEngine.class); engine.setArgs(args); try { engine.startPump(); } catch (Exception e) { logger.error("Exception Occured while doing buy/sell transaction", e); } System.out.println("\n\n\nHope you will make a profit in this pump ;)"); System.out.println("if you could make a proit using this app please conside doing some donation with 1$ or 2$ to BTC address 1PfnwEdmU3Ki9htakiv4tciPXzo49RRkai \nit will help us doing more features in the future"); }
/** * Provides a static, single instance of the application context. This method can be * called repeatedly. * <p/> * If the configuration requested differs from one used previously, then the previously-created * context is shut down. * * @return Returns an application context for the given configuration */ public synchronized static ConfigurableApplicationContext getApplicationContext(ServletContext servletContext, String[] configLocations) { AbstractApplicationContext ctx = (AbstractApplicationContext)BaseApplicationContextHelper.getApplicationContext(configLocations); CmisServiceFactory factory = (CmisServiceFactory)ctx.getBean("CMISServiceFactory"); DefaultListableBeanFactory dlbf = new DefaultListableBeanFactory(ctx.getBeanFactory()); GenericWebApplicationContext gwac = new GenericWebApplicationContext(dlbf); servletContext.setAttribute(GenericWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, gwac); servletContext.setAttribute(CmisRepositoryContextListener.SERVICES_FACTORY, factory); gwac.setServletContext(servletContext); gwac.refresh(); return gwac; }
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; }
@Test public void listenersInApplicationContextWithNestedChild() { StaticApplicationContext context = new StaticApplicationContext(); RootBeanDefinition nestedChild = new RootBeanDefinition(StaticApplicationContext.class); nestedChild.getPropertyValues().add("parent", context); nestedChild.setInitMethodName("refresh"); context.registerBeanDefinition("nestedChild", nestedChild); RootBeanDefinition listener1Def = new RootBeanDefinition(MyOrderedListener1.class); listener1Def.setDependsOn("nestedChild"); context.registerBeanDefinition("listener1", listener1Def); context.refresh(); MyOrderedListener1 listener1 = context.getBean("listener1", MyOrderedListener1.class); MyEvent event1 = new MyEvent(context); context.publishEvent(event1); assertTrue(listener1.seenEvents.contains(event1)); SimpleApplicationEventMulticaster multicaster = context.getBean( AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, SimpleApplicationEventMulticaster.class); assertFalse(multicaster.getApplicationListeners().isEmpty()); context.close(); assertTrue(multicaster.getApplicationListeners().isEmpty()); }
/** * This method makes an event firing instance of {@link org.openqa.selenium.WebDriver} * * @param driver an original instance of {@link org.openqa.selenium.WebDriver} that is * supposed to be listenable * @param listeners is a collection of {@link Listener} that * is supposed to be used for the event firing * @param <T> T * @return an instance of {@link org.openqa.selenium.WebDriver} that fires events */ @SuppressWarnings("unchecked") public static <T extends WebDriver> T getEventFiringWebDriver(T driver, Collection<Listener> listeners) { List<Listener> listenerList = new ArrayList<>(); Iterator<Listener> providers = ServiceLoader.load( Listener.class).iterator(); while (providers.hasNext()) { listenerList.add(providers.next()); } listenerList.addAll(listeners); AbstractApplicationContext context = new AnnotationConfigApplicationContext( DefaultBeanConfiguration.class); return (T) context.getBean( DefaultBeanConfiguration.WEB_DRIVER_BEAN, driver, listenerList, context); }
private AbstractApplicationContext doCreateApplicationContext() { AbstractApplicationContext context = createApplicationContext(); assertNotNull("Should have created a valid Spring application context", context); String[] profiles = activeProfiles(); if (profiles != null && profiles.length > 0) { // the context must not be active if (context.isActive()) { throw new IllegalStateException("Cannot active profiles: " + Arrays.asList(profiles) + " on active Spring application context: " + context + ". The code in your createApplicationContext() method should be adjusted to create the application context with refresh = false as parameter"); } log.info("Spring activating profiles: {}", Arrays.asList(profiles)); context.getEnvironment().setActiveProfiles(profiles); } // ensure the context has been refreshed at least once if (!context.isActive()) { context.refresh(); } return context; }
/** * Refreshes the {@link SpringContext}. */ public static void refresh() { try { logger.info("Reloading the App context: " + SpringContext.getConfigFileName()); if (ObjectUtils.isInstanceOf(appContext, AbstractApplicationContext.class)) { ((AbstractApplicationContext) appContext).refresh(); } logger.info("Successfully Reloaded the App context: " + SpringContext.getConfigFileName()); lastLoaded = System.currentTimeMillis(); } catch (Exception e) { e.printStackTrace(System.err); logger.error("Context file is not reloaded, got error while reloading the config file.", e); } }
public static void main(final String[] args) throws Exception { System.out.println("Notice this client requires that the CamelServer is already running!"); AbstractApplicationContext context = new ClassPathXmlApplicationContext("camel-client.xml"); // get the camel template for Spring template style sending of messages (= producer) ProducerTemplate camelTemplate = context.getBean("camelTemplate", ProducerTemplate.class); System.out.println("Invoking the multiply with 22"); // as opposed to the CamelClientRemoting example we need to define the service URI in this java code int response = (Integer)camelTemplate.sendBody("jms:queue:numbers", ExchangePattern.InOut, 22); System.out.println("... the result is: " + response); // we're done so let's properly close the application context IOHelper.close(context); }
public static void main(final String[] args) throws Exception { AbstractApplicationContext context = new ClassPathXmlApplicationContext("camel-file-client.xml"); // get the camel template for Spring template style sending of messages (= producer) final ProducerTemplate producer = context.getBean("camelTemplate", ProducerTemplate.class); // now send a lot of messages System.out.println("Writing files ..."); for (int i = 0; i < SIZE; i++) { producer.sendBodyAndHeader("file:target//inbox", "File " + i, Exchange.FILE_NAME, i + ".txt"); } System.out.println("... Wrote " + SIZE + " files"); // we're done so let's properly close the application context IOHelper.close(context); }
public static void main(String[] args) throws Exception { final String pckName = POIVisualizer.class.getPackage().getName(); try (AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(pckName)) { POIVisualizer visualizer = ctx.getBean(POIVisualizer.class); visualizer.start(); } System.out.println("Exiting"); }
@Test public void testCseApplicationListenerThrowException(@Injectable ContextRefreshedEvent event, @Injectable AbstractApplicationContext context, @Injectable BootListener listener, @Injectable ProducerProviderManager producerProviderManager, @Mocked RegistryUtils ru) { Map<String, BootListener> listeners = new HashMap<>(); listeners.put("test", listener); CseApplicationListener cal = new CseApplicationListener(); cal.setApplicationContext(context); ReflectUtils.setField(cal, "producerProviderManager", producerProviderManager); cal.onApplicationEvent(event); }
@Test public void testCseApplicationListenerParentNotnull(@Injectable ContextRefreshedEvent event, @Injectable AbstractApplicationContext context, @Injectable AbstractApplicationContext pContext, @Mocked RegistryUtils ru) { CseApplicationListener cal = new CseApplicationListener(); cal.setApplicationContext(context); cal.onApplicationEvent(event); }
/** * Using a full autostarting context: * Test that we can bring up and close down * a context twice without error, using it * when running. */ public void testOpenCloseOpenCloseFull() throws Exception { assertNoCachedApplicationContext(); // Open it, and use it ApplicationContext ctx = getFullContext(); assertNotNull(ctx); doTestBasicWriteOperations(ctx); // Close it down ApplicationContextHelper.closeApplicationContext(); assertNoCachedApplicationContext(); // Re-open it, we get a fresh copy ApplicationContext ctx2 = getFullContext(); assertNotNull(ctx2); doTestBasicWriteOperations(ctx2); // Ask for it again, will be no change this time ctx = getFullContext(); assertEquals(ctx, ctx2); // Refresh it, shouldn't break anything ((AbstractApplicationContext)ctx).refresh(); // And finally close it ApplicationContextHelper.closeApplicationContext(); assertNoCachedApplicationContext(); }
@Test public void containsDocumentDbFactory() throws ClassNotFoundException { final AbstractApplicationContext context = new AnnotationConfigApplicationContext( TestDocumentDbConfiguration.class); Assertions.assertThat(context.getBean(DocumentDbFactory.class)).isNotNull(); }
@Override public void postProcessBeanFactory (ConfigurableListableBeanFactory bf) throws BeansException { bf.setParentBeanFactory ( ((AbstractApplicationContext) ApplicationContextProvider .getApplicationContext ()).getBeanFactory ()); }
protected static BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) { if (context instanceof BeanDefinitionRegistry) { return (BeanDefinitionRegistry) context; } if (context instanceof AbstractApplicationContext) { return (BeanDefinitionRegistry) ((AbstractApplicationContext) context).getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); }
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; }
public static void main(String[] args) { AbstractApplicationContext ctx=new ClassPathXmlApplicationContext("com/app/annotation_config/config.xml"); Object ob=ctx.getBean("Annotation"); model mod=(model)ob; System.out.println("\t\t"+mod); ctx.registerShutdownHook(); }
@Before public void init() throws Throwable { stubDemo(); pluginDao.refresh(); initGit(); if (Files.exists(Paths.get(gitWorkspace.toString(), "plugin_cache.json"))) { Files.delete(Paths.get(gitWorkspace.toString(), "plugin_cache.json")); } applicationEventMulticaster = (ApplicationEventMulticaster) applicationContext .getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME); }
public static void main(String args[]) { AbstractApplicationContext ctx=new ClassPathXmlApplicationContext("com/app/xml_config/config.xml"); Object ob=ctx.getBean("model"); model_spring_bean mod=(model_spring_bean)ob; System.out.println("\t\t"+mod); ctx.registerShutdownHook(); }
public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new ClassPathXmlApplicationContext("beans_lifecycle.xml"); Demo_Custom_Init obj=(Demo_Custom_Init)context.getBean("obj"); System.out.println(obj); ((AbstractApplicationContext)context).registerShutdownHook(); }
public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new ClassPathXmlApplicationContext("beans_lifecycle.xml"); Demo_DisposableBean obj=(Demo_DisposableBean)context.getBean("obj_Disposable"); System.out.println(obj); ((AbstractApplicationContext)context).registerShutdownHook(); }
public synchronized void load(AbstractApplicationContext abstractApplicationContext) { this.abstractApplicationContext = Objects.requireNonNull(abstractApplicationContext, "unexpect error"); Map<String, Action> actionMap = abstractApplicationContext.getBeansOfType(Action.class); for (Map.Entry<String, Action> entry : actionMap.entrySet()) { Action action = entry.getValue(); parse(action); } }
@Override public void initialize(AbstractApplicationContext applicationContext) { PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer(); //load test.properties propertyPlaceholderConfigurer.setLocation(new ClassPathResource("test.properties")); applicationContext.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer); }
@Test // SPR-6354 public void destroyLazyInitSchedulerWithDefaultShutdownOrderDoesNotHang() { AbstractApplicationContext context = new ClassPathXmlApplicationContext("quartzSchedulerLifecycleTests.xml", this.getClass()); assertNotNull(context.getBean("lazyInitSchedulerWithDefaultShutdownOrder")); 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 // 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); }
protected static synchronized AbstractApplicationContext getApplicationContext() { if (applicationContext == null) { String[] filenames = { "/performance/applicationContext-service.xml" }; applicationContext = new ClassPathXmlApplicationContext(filenames); } return applicationContext; }
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Bean(name = WEB_DRIVER_BEAN) public <T extends WebDriver> T getListenableWebdriver(T driver, List<Listener> listeners, AbstractApplicationContext context) { this.driver = driver; this.listeners.addAll(listeners); this.context = context; return driver; }
@Override protected AbstractApplicationContext createApplicationContext() { ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("META-INF/spring/test-spring-context.xml"); userRepository = (UserRepository) context.getBean("userRepository"); subscriberRepository = (SubscriberRepository) context.getBean("subscriberRepository"); testUser = (User) context.getBean("testUser"); testSubscriber = (Subscriber) context.getBean("testSubscriber"); builder = context.getBean(Rss2XmlHandler.class); return context; }
/** * Shutdowns the {@link SpringContextProvider} safely.. */ public static void shutdown() { if (ObjectUtils.isNotNull(appContext)) { logger.info("Destroying the App context: " + SpringContext.getConfigFileName()); if (appContext instanceof AbstractApplicationContext) { ((AbstractApplicationContext) appContext).destroy(); } logger.info("Successfully Destroyed the App context: " + SpringContext.getConfigFileName()); } }
@Test public void doesNotRegistersShutdownHook() throws Exception { // See gh-314 for background. We no longer register the shutdown hook // since it is really the callers responsibility. The shutdown hook could // also be problematic in a classic WAR deployment. addEmbeddedServletContainerFactoryBean(); this.context.refresh(); Field shutdownHookField = AbstractApplicationContext.class .getDeclaredField("shutdownHook"); shutdownHookField.setAccessible(true); Object shutdownHook = shutdownHookField.get(this.context); assertThat(shutdownHook).isNull(); }
private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) { if (context instanceof BeanDefinitionRegistry) { return (BeanDefinitionRegistry) context; } if (context instanceof AbstractApplicationContext) { return (BeanDefinitionRegistry) ((AbstractApplicationContext) context) .getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); }
@Override protected AbstractApplicationContext createApplicationContext() { AnnotationConfigApplicationContext springContext = new AnnotationConfigApplicationContext(); springContext.register(SpringLdapTestConfiguration.class); springContext.refresh(); return springContext; }
/** * Get the bean definition registry. * @param context the application context * @return the BeanDefinitionRegistry if it can be determined */ private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) { if (context instanceof BeanDefinitionRegistry) { return (BeanDefinitionRegistry) context; } if (context instanceof AbstractApplicationContext) { return (BeanDefinitionRegistry) ((AbstractApplicationContext) context) .getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); }
@Test public void checkProducerBeanInjection() { AbstractApplicationContext applicationContext = createApplicationContext(); MyProduceBean bean = applicationContext.getBean("myProduceBean", MyProduceBean.class); assertNotNull("The producerTemplate should not be null.", bean.getProducerTemplate()); assertEquals("Get a wrong response", "Camel rocks!", bean.getProducerTemplate().requestBody("Camel")); }