@Override public void onApplicationEvent(ApplicationEvent event) { if (event.getClass() == ContextRefreshedEvent.class) { logger.info("register url: " + infoHolder.taskProtocolUrl()); extensionLoader.loadExtension(Registry.class).doRegister(infoHolder.taskProtocolUrl()); try { extensionLoader.loadExtension(ProtocolFactory.class).server().openServer(infoHolder.taskProtocolUrl()); } catch (Exception e) { throw new RuntimeException(e); } sandbox.configSandbox(); } else if (event.getClass() == ContextClosedEvent.class) { logger.info("unregister url: " + infoHolder.taskProtocolUrl()); extensionLoader.loadExtension(Registry.class).unRegister(infoHolder.taskProtocolUrl()); extensionLoader.loadExtension(ProtocolFactory.class).server().close(); } }
@EventListener(value = ContextRefreshedEvent.class) public void init() { log.info("start data initialization ..."); this.posts .deleteAll() .thenMany( Flux .range(1, 1000) .flatMap( num -> this.posts.save(Post.builder().title("Title" + num).content("content of " + "Title" + num).build()) ) ) .log() .subscribe( null, null, () -> log.info("done initialization...") ); }
@EventListener(value = ContextRefreshedEvent.class) public void init() { log.info("start data initialization ..."); this.posts .deleteAll() .thenMany( Flux .just("Post one", "Post two") .flatMap( title -> this.posts.save(Post.builder().title(title).content("content of " + title).build()) ) ) .log() .subscribe( null, null, () -> log.info("done initialization...") ); }
@EventListener(value = ContextRefreshedEvent.class) public void init() { log.info("start data initialization ..."); this.posts .deleteAll() .thenMany( Flux .range(1, 100) .flatMap( num -> this.posts.save(Post.builder().title("Title" + num).content("content of " + "Title" + num).build()) ) ) .log() .subscribe( null, null, () -> log.info("done initialization...") ); }
@EventListener(value = ContextRefreshedEvent.class) public void init() { log.info("start data initialization ..."); this.posts .deleteAll() .thenMany( Flux .just("Post one", "Post two") .flatMap( title -> this.posts.save(Post.builder().id(UUID.randomUUID().toString()).title(title).content("content of " + title).build()) ) ) .log() .subscribe( null, null, () -> log.info("done initialization...") ); }
/** * Run setup when application starts. */ @EventListener(ContextRefreshedEvent.class) public void contextRefreshedEvent() { logger.info("Running setup"); if (userRepository.count() == 0) { logger.info("No users have been configured, creating default user"); User user = new User(defaultUsername, defaultPassword, Collections.singleton("ROLE_" + WebSecurityConfig.Roles.ADMIN)); userRepository.save(user); logger.info("Created user \"{}\" with password \"{}\". Change this password for security reasons!", defaultUsername, defaultPassword); } logger.info("Setup completed"); }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext)event.getApplicationContext(); Map<String,Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(ThriftServiceApi.class); ServiceMap serviceMap=new ServiceMap(); for(String name:beansWithAnnotation.keySet()){ Object obj = beansWithAnnotation.get(name); Class[] interfaces=obj.getClass().getInterfaces(); for(Class i:interfaces) if(i.getAnnotation(ThriftServiceApi.class)!=null){ serviceMap.addService(i.getName(),obj); } } applicationContext.getBeanFactory().registerSingleton(serviceMap.getClass().getName(),serviceMap); }
/** * Start the scheduler. * Method called after Spring has finished initializing the Application Context, so that YadaPersistentEnums have been initialized. * @param event * @throws Exception */ @EventListener public void init(ContextRefreshedEvent event) { if (initialized.getAndSet(true)) { return; } // It is itself scheduled by a TaskScheduler configured in YadaAppConfig and run every config/yada/jobSchedulerPeriodMillis milliseconds log.debug("init called"); long period = config.getYadaJobSchedulerPeriod(); if (period>0) { // Disable any job that is already RUNNING but jobRecoverable is false yadaJobDao.setUnrecoverableJobState(); // Recover any job that is still in the RUNNING state and its group is not paused List<YadaJob> recoverableJobs = yadaJobDao.getRecoverableJobs(); for (YadaJob yadaJob : recoverableJobs) { yadaJob.setRecovered(true); yadaJob.setJobStartTime(new Date()); // Needed to prevent stale cleaning yadaJobRepository.save(yadaJob); yadaJobScheduler.runJob(yadaJob.getId()); } // Scheduling the YadaJobScheduler according to the configured period yadaJobSchedulerTaskScheduler.scheduleAtFixedRate(yadaJobScheduler, new Date(System.currentTimeMillis() + 10000), period); } else { log.info("YadaJobScheduler not started"); } }
@EventListener public void onApplicationEvent(ContextRefreshedEvent event) { logger.info("ContextRefreshedEvent"); ApplicationContext applicationContext = event.getApplicationContext(); logger.info("Found " + services.size() + " services"); ErraiServiceSingleton.registerInitCallback(new ErraiServiceSingleton.ErraiInitCallback() { @SuppressWarnings("rawtypes") @Override public void onInit(ErraiService service) { logger.info("Subscribing " + services.size() + " services."); for (ServiceImplementation serviceImplementation : services) { subscribe(applicationContext, service, serviceImplementation); } } }); }
public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextClosedEvent) { enabled = false; return; } if (event instanceof ContextRefreshedEvent) { initialized = true; return; } if (event instanceof OsgiServiceDependencyWaitStartingEvent) { if (enabled) { OsgiServiceDependencyWaitStartingEvent evt = (OsgiServiceDependencyWaitStartingEvent) event; String[] filter = new String[] { evt.getServiceDependency().getServiceFilter().toString() }; BlueprintEvent waitingEvent = new BlueprintEvent(BlueprintEvent.WAITING, bundleContext.getBundle(), extenderBundle, filter); listenerManager.blueprintEvent(waitingEvent); dispatcher.waiting(waitingEvent); } return; } }
@Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { // root application context if(null == contextRefreshedEvent.getApplicationContext().getParent()) { logger.debug(">>>>> spring初始化完毕 <<<<<"); // spring初始化完毕后,通过反射调用所有使用BaseService注解的initMapper方法 Map<String, Object> baseServices = contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(BaseService.class); for(Map.Entry<String, Object> entry : baseServices.entrySet()){ System.out.println(entry.getKey() + "," + entry.getValue()); } for(Object service : baseServices.values()) { logger.debug(">>>>> {}.initMapper()", service.getClass().getName()); try { Method initMapper = service.getClass().getMethod("initMapper"); initMapper.invoke(service); } catch (Exception e) { logger.error("初始化BaseService的initMapper方法异常", e); e.printStackTrace(); } } } }
@Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { //模块执行完会执行该方法 logger.debug("开始扫描模块"); //获取所有有模块注解的对象 Map<String, Object> beans = contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(Module.class); List<com.carl.wolf.core.bean.Module> modules = new ArrayList<>(); for (Object value : beans.values()) { try { //处理获取模块并且添加到容器 if (scanStrategy.support(value)) { modules.add(scanStrategy.process(value)); } } catch (ModuleScanException e) { logger.error("模块扫描异常", e); } } }
@Override public void onApplicationEvent ( ContextRefreshedEvent event ) { final RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext.getBean( RequestMappingHandlerMapping.class ); final Map< RequestMappingInfo, HandlerMethod > handlerMethods = requestMappingHandlerMapping.getHandlerMethods(); this.handlerMethods = handlerMethods; handlerMethods.keySet().forEach( mappingInfo -> { Map< Set< String >, Set< RequestMethod > > mapping = Collections.singletonMap( mappingInfo.getPatternsCondition().getPatterns() , this.getMethods( mappingInfo.getMethodsCondition().getMethods() ) ); requestMappingInfos.add( mapping ); } ); requestMappingUris.addAll( handlerMethods.keySet() .parallelStream() .map( mappingInfo -> mappingInfo.getPatternsCondition().getPatterns() ) .collect( Collectors.toList() ) ); }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { // Spring context initialized trigger if (event.getApplicationContext().getParent() == null) { loadProcessor(event); } // spring web root initialized trigger if (event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")) { if (processorLogicDefination.size()==0) { loadProcessor(event); } } System.out.println(JSON.toJSONString(processorLogicDefination,true)); }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { if(event.getApplicationContext().getParent() == null){ //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。 System.out.println("spring 加载完毕.."); new ApplicationFactory().setApplicationContext(event.getApplicationContext()); try { NettyServer.getInstance().start(); } catch (Exception e) { e.printStackTrace(); } } }
@Test public void testNoParentForApplicationContext() { JpaMedia mockJdkMedia = mock(JpaMedia.class); when(mockJdkMedia.getType()).thenReturn(MediaType.JDK); List<JpaMedia> mediaList = Collections.singletonList(mockJdkMedia); when(Config.mediaServiceMock.findAll()).thenReturn(mediaList); ContextRefreshedEvent mockStartupEvent = mock(ContextRefreshedEvent.class); ApplicationContext mockApplicationContext = mock(ApplicationContext.class); when(mockStartupEvent.getApplicationContext()).thenReturn(mockApplicationContext); applicationContextListener.handleEvent(mockStartupEvent); verify(Config.jvmServiceMock, never()).updateJvm(any(UpdateJvmRequest.class), eq(true)); verify(Config.mediaServiceMock, never()).create(anyMap(), anyMap()); }
/** * On context refreshed event, merges singleton instance * of the registry with custom bean instance of the registry. */ @EventListener(ContextRefreshedEvent.class) public void contextRefreshEvent() { MapConfigurationRegistrySingleton.getSingleton() .merge(mapConfigurationRegistry); }
@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); }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext().getParent() == null) { initService.setProductAndUser(); } }
@Override public void onApplicationEvent(ApplicationEvent event) { if (event.getClass() == ContextRefreshedEvent.class) { extensionLoader.loadExtension(Registry.class).subscribe(); extensionLoader.loadExtension(ProtocolFactory.class).client().open(); extensionLoader.loadExtension(Selector.class).start(); logger.info("subscribe:" + extensionLoader.loadExtension(Registry.class).getDirectory().list()); latch.countDown(); } else if (event.getClass() == ContextClosedEvent.class) { logger.info("unSubscribe task"); extensionLoader.loadExtension(Registry.class).unSubscribe(); extensionLoader.loadExtension(ProtocolFactory.class).client().close(); extensionLoader.loadExtension(Selector.class).close(); } }
@Override public void onApplicationEvent(ApplicationEvent event) { // Once the context has been refreshed, we tell other interested beans // about the existence of this content store // (e.g. for monitoring purposes) if (event instanceof ContextRefreshedEvent && event.getSource() == this.applicationContext) { ApplicationContext context = ((ContextRefreshedEvent) event).getApplicationContext(); context.publishEvent(new ContentStoreCreatedEvent(this, Collections.<String, Serializable>emptyMap())); } }
@EventListener(ContextRefreshedEvent.class) public void initPosts() { log.info("initializing posts data..."); Stream.of("Post one", "Post two").forEach( title -> this.posts.save(Post.builder().title(title).content("content of " + title).build()) .subscribe() ); }
public void start(ContextRefreshedEvent event) { if (event.getApplicationContext() == this.context) { if (this.eager && this.registry != null) { for (String name : this.context.getBeanDefinitionNames()) { BeanDefinition definition = this.registry.getBeanDefinition(name); if (this.getName().equals(definition.getScope()) && !definition.isLazyInit()) { this.context.getBean(name); } } } } }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext() == this.applicationContext) { registerConfigWatchers(); watch(); } }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { if (!errorMessages.isEmpty()) { throw new IllegalArgumentException("unable to collect queue beans:" + System.lineSeparator() + errorMessages.stream().collect(Collectors.joining(System.lineSeparator()))); } }
public void onApplicationEvent(ApplicationEvent event) { //只监听容器刷新事件ContextRefreshedEvent if (ContextRefreshedEvent.class.getName().equals(event.getClass().getName())) { //isDelay为true,并且没有被导出服务,并且没有被停止导出服务 if (isDelay() && ! isExported() && ! isUnexported()) { if (logger.isInfoEnabled()) { logger.info("The service ready on spring started. service: " + getInterface()); } //父类ServiceConfig中实现的方法 export(); } } }
/** * @desc 启动时初始化定时压测任务 * * @author liuliang * */ @Override public void onApplicationEvent(ContextRefreshedEvent event) { logger.info("---初始化自动化压测任务----"); try { List<AutomaticTaskBO> dataList = automaticTaskService.getDataList(0,automaticTaskService.getCount()); if((null != dataList) && (0 < dataList.size())){ for(AutomaticTaskBO automaticTaskBO:dataList){ this.syncAutomaticTask(automaticTaskBO,TaskSyncTypeEnum.UPDATE.value); } } } catch (Exception e) { logger.error("初始化所有自动压测任务异常",e); } }
public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { ContextRefreshedEvent refreshEvent = (ContextRefreshedEvent)event; ApplicationContext refreshContext = refreshEvent.getApplicationContext(); if (refreshContext != null && refreshContext.equals(applicationContext)) { // Initialize the bean init(); } } }
private void publishDiscoveryEvent() { if (this.config == null) { return; } final IndexEvent discoveryEvent = new IndexEvent(this, "Discovery", 1); final ConfigurableApplicationContext applicationContext = this.config.getApplicationContext(); try { applicationContext.publishEvent(discoveryEvent); } catch (IllegalStateException e) { // There's a possibility that the application context hasn't fully refreshed yet, so register a listener // that will fire when it has applicationContext.addApplicationListener(new ApplicationListener() { public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { applicationContext.publishEvent(discoveryEvent); } } }); } }
public void onApplicationEvent(ApplicationEvent event) { // Once the context has been refreshed, we tell other interested beans about the existence of this content store // (e.g. for monitoring purposes) if (event instanceof ContextRefreshedEvent && event.getSource() == this.applicationContext) { publishEvent(((ContextRefreshedEvent) event).getApplicationContext(), Collections.<String, Serializable> emptyMap()); } }
@Override public void multicastEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent && event.getSource() == this.appContext) { this.isApplicationStarted = true; for (ApplicationEvent queuedEvent : this.queuedEvents) { multicastEventInternal(queuedEvent); } this.queuedEvents.clear(); multicastEventInternal(event); } else if (event instanceof ContextClosedEvent && event.getSource() == this.appContext) { this.isApplicationStarted = false; multicastEventInternal(event); } else if (this.isApplicationStarted) { multicastEventInternal(event); } else { this.queuedEvents.add(event); } }
@Override public void publishEvent(ApplicationEvent event) { Assert.notNull(event, "Event must not be null"); if (logger.isTraceEnabled()) { logger.trace("Publishing event in " + getDisplayName() + ": " + event); } ((ApplicationEventMulticaster) getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)).multicastEvent(event); if (!(getParent() == null || event instanceof ContextRefreshedEvent || event instanceof ContextClosedEvent)) { getParent().publishEvent(event); } }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { EntityManager em = (EntityManager) event.getApplicationContext().getBean("entityManagerPrimary"); Set<EntityType<?>> entitys = em.getMetamodel().getEntities(); Iterator<EntityType<?>> iter = entitys.iterator(); while(iter.hasNext()){ EntityType<?> et = iter.next(); ClassCache.setValueByClass(et.getJavaType()); } }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { if(event.getApplicationContext().getParent()==null) { setLocale(); } }
/** * {@inheritDoc} */ public void onApplicationEvent(ApplicationEvent event) { if (failFast && event instanceof ContextRefreshedEvent) { // fail-fast -> check all statements are completed this.sqlSessionFactory.getConfiguration().getMappedStatementNames(); } }