类org.springframework.boot.context.event.ApplicationStartedEvent源码实例Demo

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

源代码1 项目: openvsx   文件: LicenseInitializer.java
@EventListener
@Transactional
public void initExtensionLicenses(ApplicationStartedEvent event) {
    var detection = new LicenseDetection(Arrays.asList(detectLicenseIds));
    var undetected = new int[1];
    repositories.findVersionsByLicense(null).forEach(extVersion -> {
        var license = repositories.findFile(extVersion, FileResource.LICENSE);
        if (license != null) {
            var detectedId = detection.detectLicense(license.getContent());
            if (detectedId == null) {
                undetected[0]++;
            } else {
                extVersion.setLicense(detectedId);
                var extension = extVersion.getExtension();
                logger.info("License of " + extension.getNamespace().getName() + "." + extension.getName()
                        + " v" + extVersion.getVersion() + " set to " + detectedId);
            }
        }
    });

    if (undetected[0] > 0)
        logger.warn("Failed to detect license type for " + undetected[0] + " extensions.");
}
 
源代码2 项目: spring-examples   文件: HazelcastApplication.java
@EventListener(ApplicationStartedEvent.class)
public void generateDefaultData() {
    Long count = carRepository.count();
    if (count == 0L) {
        List<String> colors = List.of("Black", "White", "Red", "Blue");
        List<Car> carList = new ArrayList<>();
        Date newDate = new Date();
        for (int i = 0; i < 500; i++) {
            carList.add(
                    Car.builder()
                            .brand("HKCar")
                            .colour(colors.get(i % 3))
                            .date(newDate)
                            .doorCount(4)
                            .fuel("Diesel")
                            .model("SuperCar")
                            .serial("SR" + i)
                            .type("TypeC")
                            .year(2020)
                            .build()
            );
        }
        carRepository.saveAll(carList);
    }
}
 
源代码3 项目: x7   文件: RepositoryListener.java
private void customizeDataTransform(ApplicationStartedEvent applicationStartedEvent) {
    DataTransformCustomizer customizer = null;
    try {
        customizer = applicationStartedEvent.getApplicationContext().getBean(DataTransformCustomizer.class);
    } catch (Exception e) {

    }

    if (customizer == null)
        return;

    DataTransform dataTransform = customizer.customize();
    if (dataTransform == null)
        return;

    Repository repository = applicationStartedEvent.getApplicationContext().getBean(Repository.class);
    if (repository == null)
        return;
    ((CacheableRepository) repository).setDataTransform(dataTransform);
}
 
源代码4 项目: x7   文件: RepositoryListener.java
private void customizeL2CacheConsistency(ApplicationStartedEvent applicationStartedEvent) {
    L2CacheConsistencyCustomizer customizer = null;
    try {
        customizer = applicationStartedEvent.getApplicationContext().getBean(L2CacheConsistencyCustomizer.class);
    } catch (Exception e) {

    }

    if (customizer == null || customizer.customize() == null)
        return;

    L2CacheResolver levelTwoCacheResolver = applicationStartedEvent.getApplicationContext().getBean(L2CacheResolver.class);
    if (levelTwoCacheResolver == null)
        return;
    levelTwoCacheResolver.setL2CacheConsistency(customizer.customize());
}
 
源代码5 项目: tomato   文件: TomatoStartListener.java
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
    if (applicationEvent instanceof ApplicationStartedEvent) {
        Idempotent idempotent = applicationContext.getBean(Idempotent.class);
        if (idempotent != null) {
            Banner.print();
        }
    }
}
 
源代码6 项目: openvsx   文件: SearchService.java
@EventListener
@Transactional
public void initSearchIndex(ApplicationStartedEvent event) {
    if (!isEnabled()) {
        return;
    }
    var stopWatch = new StopWatch();
    stopWatch.start();
    updateSearchIndex();
    stopWatch.stop();
    logger.info("Initialized search index in " + stopWatch.getTotalTimeMillis() + " ms");
}
 
源代码7 项目: openvsx   文件: VersionInitializer.java
@EventListener
@Transactional
public void initExtensionLicenses(ApplicationStartedEvent event) {
    var count = new int[2];
    repositories.findAllExtensions().forEach(extension -> {
        ExtensionVersion latest = null;
        SemanticVersion latestVer = null;
        ExtensionVersion preview = null;
        SemanticVersion previewVer = null;
        for (var extVersion : extension.getVersions()) {
            var ver = new SemanticVersion(extVersion.getVersion());
            if (extVersion.isPreview() && isGreater(extVersion, ver, preview, previewVer)) {
                preview = extVersion;
                previewVer = ver;
            } else if (!extVersion.isPreview() && isGreater(extVersion, ver, latest, latestVer)) {
                latest = extVersion;
                latestVer = ver;
            }
        }
        if (latest != null && latest != extension.getLatest()) {
            extension.setLatest(latest);
            count[0]++;
        }
        if (preview != null && preview != extension.getPreview()) {
            extension.setPreview(preview);
            count[1]++;
        }
    });

    if (count[0] > 0)
        logger.info("Updated latest version for " + count[0] + " extensions.");
    if (count[1] > 0)
        logger.info("Updated preview version for " + count[1] + " extensions.");
}
 
源代码8 项目: SENS   文件: StartedListener.java
@Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        try {
            this.loadActiveTheme();
        } catch (TemplateModelException e) {
            e.printStackTrace();
        }
        this.loadOptions();
        this.loadOwo();
        //启动定时任务
//        CronUtil.start();
        log.info("The scheduled task starts successfully!");
    }
 
源代码9 项目: spring-examples   文件: WebfluxApplication.java
@EventListener(ApplicationStartedEvent.class)
public void appStart() {
    if (employeeRepository.count().block() == 0) {
        IntStream.range(0, 100)
                .mapToObj(this::generate)
                .map(employeeRepository::save)
                .collect(Collectors.toList())
                .forEach(item -> item.subscribe(System.out::println));
    }
}
 
源代码10 项目: stone   文件: StartedListener.java
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    try {
        this.loadActiveTheme();
    } catch (TemplateModelException e) {
        e.printStackTrace();
    }
    this.loadOptions();
    this.loadThemes();
    this.loadOwo();
    //启动定时任务
    CronUtil.start();
    log.info("The scheduled task starts successfully!");
}
 
源代码11 项目: sbp   文件: MainAppStartedListener.java
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    pluginManager.getPlugins(PluginState.STARTED).forEach(pluginWrapper -> {
        SpringBootPlugin springBootPlugin = (SpringBootPlugin) pluginWrapper.getPlugin();
        ApplicationContext pluginAppCtx = springBootPlugin.getApplicationContext();
        pluginAppCtx.publishEvent(new SbpMainAppStartedEvent(applicationContext));
    });
    pluginManager.setMainApplicationStarted(true);
}
 
public static void main(String[] args) {
    new SpringApplicationBuilder(Object.class)
            .listeners((ApplicationListener<ApplicationStartedEvent>) event -> {
                System.out.println("监听 Spring Boot 事件 ApplicationStartedEvent");
            }, (ApplicationListener<ApplicationStartingEvent>) event -> {
                System.out.println("监听 Spring Boot 事件 ApplicationStartingEvent ");
            })
            .web(false) // 非 Web 应用
            .run(args)  // 运行 SpringApplication
            .close();   // 关闭 Spring 应用上下文
}
 
源代码13 项目: Taroco   文件: RouteConfigInitListener.java
/**
 * Callback used to run the bean.
 * 初始化路由配置的数据,避免gateway 依赖业务模块
 */
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    log.info("开始初始化路由配置数据");
    QueryWrapper<SysRoute> wrapper = new QueryWrapper<>();
    wrapper.eq(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
    List<SysRoute> routeList = sysRouteService.list(wrapper);
    if (!CollectionUtils.isEmpty(routeList)) {
        redisRepository.set(CacheConstants.ROUTE_KEY, JsonUtils.toJsonString(routeList));
        log.info("更新Redis中路由配置数据:{}条", routeList.size());
    }
    log.info("初始化路由配置数据完毕");
}
 
源代码14 项目: BlogManagePlatform   文件: ValidateCodeChecker.java
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
	try {
		if (codeChecker.needCheck()) {
			log.info("[frodez.config.validator.ValidateChecker]hibernate-validator代码校验开始");
			check();
			log.info("[frodez.config.validator.ValidateChecker]hibernate-validator代码校验结束");
		} else {
			log.info("[frodez.config.validator.ValidateChecker]未开启hibernate-validator代码校验功能");
		}
	} catch (IOException | ClassNotFoundException | LinkageError e) {
		log.error("[frodez.config.validator.ValidateChecker]发生错误,程序终止", e);
		ContextUtil.exit();
	}
}
 
源代码15 项目: blog-sharon   文件: StartedListener.java
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    try {
        this.loadActiveTheme();
    } catch (TemplateModelException e) {
        e.printStackTrace();
    }
    this.loadOptions();
    this.loadThemes();
    this.loadOwo();
    //启动定时任务
    CronUtil.start();
    log.info("The scheduled task starts successfully!");
}
 
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    List<BindingParam> bindingParams = new ArrayList<>();
    bindingParams.add(new RestBindingParam());

    ServiceParam serviceParam = new ServiceParam();
    serviceParam.setInterfaceType(SwaggerService.class);
    serviceParam.setInstance(new SwaggerServiceImpl());
    serviceParam.setBindingParams(bindingParams);

    ServiceClient serviceClient = clientFactory.getClient(ServiceClient.class);
    serviceClient.service(serviceParam);
}
 
源代码17 项目: halo   文件: StartedListener.java
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
    try {
        this.migrate();
    } catch (SQLException e) {
        log.error("Failed to migrate database!", e);
    }
    this.initThemes();
    this.initDirectory();
    this.printStartInfo();
}
 
源代码18 项目: halo   文件: FreemarkerConfigAwareListener.java
@EventListener
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public void onApplicationStartedEvent(ApplicationStartedEvent applicationStartedEvent) throws TemplateModelException {
    log.debug("Received application started event");

    loadThemeConfig();
    loadOptionsConfig();
    loadUserConfig();
}
 
/**
 * This event is executed as late as conceivably possible to indicate that 
 * the application is ready to service requests.
 */

@Override
public void onApplicationEvent(final ApplicationStartedEvent applicationStartedEvent) {
	//System.out.println("DEBUGGING: Found new Spring Boot App property : " + applicationStartedEvent.getApplicationContext().getEnvironment().getProperty("spring.cloud.stream.bindings.input.group"));

	System.out.println("======= ApplicationStartingEvent ===== ");
    System.out.println("What is the Event Hubs Consumer Group Name?");
	System.out.println("NOTIFICATIONS_EVENT_HUB_CONSUMER_GROUP_NAME=" +
			applicationStartedEvent.
					getApplicationContext().
					getEnvironment().
					getProperty("spring.cloud.stream.bindings.input.group"));
}
 
源代码20 项目: x7   文件: ReyListener.java
private void customizeRestTemplate(ApplicationStartedEvent event) {

        try {
            RestTemplateCustomizer bean = event.getApplicationContext().getBean(RestTemplateCustomizer.class);
            if (bean == null)
                return;
            SimpleRestTemplate simpleRestTemplate = bean.customize();
            if (simpleRestTemplate == null)
                return;
            HttpClientResolver.setRestTemplate(simpleRestTemplate);
        }catch (Exception e) {

        }
    }
 
源代码21 项目: x7   文件: RepositoryListener.java
private void txConfig(ApplicationStartedEvent event){
    try {
        PlatformTransactionManager platformTransactionManager = event.getApplicationContext().getBean(PlatformTransactionManager.class);
        if (platformTransactionManager == null)
            return;
        new TxConfig(platformTransactionManager);
    }catch (Exception e){

    }
}
 
源代码22 项目: joinfaces   文件: JoinfacesApplicationAnalyzer.java
@SuppressWarnings("unchecked")
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
	try {
		Class<? extends Annotation> managedBeanClass = (Class<? extends Annotation>) Class.forName("javax.faces.bean.ManagedBean");
		warnAboutJsfManagedBeans(event.getApplicationContext(), managedBeanClass);
	}
	catch (ClassNotFoundException | LinkageError ignored) {
	}
}
 
@Test
public void testJsfManagedBeans() {
	this.applicationContextRunner
			.withUserConfiguration(DummyConfiguration.class)
			.run(context -> {
				assertThat(context.getBeanNamesForAnnotation(ManagedBean.class)).isNotEmpty();

				ApplicationStartedEvent applicationStartedEvent = mock(ApplicationStartedEvent.class);
				when(applicationStartedEvent.getApplicationContext()).thenReturn(context.getSourceApplicationContext());

				this.joinfacesApplicationAnalyzer.onApplicationEvent(applicationStartedEvent);
			});
}
 
@Test
public void issue_notDecryptedDuringBoostrapPhase() {
	// making spring.cloud.bootstrap.enabled=true in order to bootstrap the application.
	// making jasypt.encryptor.bootstrap=false otherwise JasyptSpringCloudBootstrapConfiguration becomes active.
	startWith(new BaseBootstrappingTestListener() {
		
		@Override
		public void onApplicationEvent(final ApplicationStartedEvent event) {
			assertEquals("ENC() value is not decrypted during bootstrap phase", "mypassword", event.getApplicationContext().getEnvironment().getProperty("spring.cloud.config.server.svn.password"));
		}
	}, "--spring.cloud.bootstrap.enabled=true", "--jasypt.encryptor.bootstrap=false");
	
	assertNotNull(this.context.getBean(EnableEncryptablePropertiesBeanFactoryPostProcessor.class));
}
 
@Test
public void fix_decryptedDuringBoostrapPhase() {
	// making spring.cloud.bootstrap.enabled=true in order to bootstrap the application.
	// making jasypt.encryptor.bootstrap=true in order to bootstrap Jasypt.
	startWith(new BaseBootstrappingTestListener() {
		
		@Override
		public void onApplicationEvent(final ApplicationStartedEvent event) {
			assertEquals("ENC() value is decrypted during bootstrap phase", "mypassword", event.getApplicationContext().getEnvironment().getProperty("spring.cloud.config.server.svn.password"));
		}
	}, "--spring.cloud.bootstrap.enabled=true", "--jasypt.encryptor.bootstrap=true");
	
	assertNotNull(this.context.getBean(EnableEncryptablePropertiesBeanFactoryPostProcessor.class));
}
 
@Test
public void encryptableBFPPBeanCreatedWhenBoostrapTrue() {
	startWith(new BaseBootstrappingTestListener() {

		@Override
		public void onApplicationEvent(final ApplicationStartedEvent event) {
			assertEquals("ENC() value is decrypted during bootstrap phase", "mypassword", event.getApplicationContext().getEnvironment().getProperty("spring.cloud.config.server.svn.password"));
		}
	}, "--spring.cloud.bootstrap.enabled=true");
	assertNotNull("EnableEncryptablePropertiesBeanFactoryPostProcessor not created when spring.cloud.bootstrap.enabled=true", 
			this.context.getBean(EnableEncryptablePropertiesBeanFactoryPostProcessor.class));
}
 
@Test
public void encryptableBFPPBeanCreatedWhenBoostrapFalse() {
	startWith(new BaseBootstrappingTestListener() {

		@Override
		public void onApplicationEvent(final ApplicationStartedEvent event) {
			assertNotEquals("ENC() value is decrypted during bootstrap phase", "mypassword", event.getApplicationContext().getEnvironment().getProperty("spring.cloud.config.server.svn.password"));
		}
	}, "--spring.cloud.bootstrap.enabled=false");
	assertNotNull("EnableEncryptablePropertiesBeanFactoryPostProcessor not created when spring.cloud.bootstrap.enabled=false", 
			this.context.getBean(EnableEncryptablePropertiesBeanFactoryPostProcessor.class));
}
 
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
	
	SpringApplication app = event.getSpringApplication();
       app.setBannerMode(Mode.OFF);
       
	logger.info("1 spring boot启动, StartedEventApplicationListener...");
}
 
源代码29 项目: cim   文件: CIMConfig.java
@Override
public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {

	appHandlerMap.put("client_bind",applicationContext.getBean(BindHandler.class));
	appHandlerMap.put("client_closed",applicationContext.getBean(SessionClosedHandler.class));

	applicationContext.getBean(CIMNioSocketAcceptor.class).bind();
}
 
源代码30 项目: Milkomeda   文件: DelayTimer.java
@Override
public void onApplicationEvent(@NonNull ApplicationStartedEvent event) {
    taskScheduler.scheduleWithFixedDelay(delegatingDelayJobHandler, props.getDelayBucketPollRate());
}
 
 类所在包
 同包方法