org.springframework.boot.ApplicationRunner Java Examples

The following examples show how to use org.springframework.boot.ApplicationRunner. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EmbeddedTestApplication.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
@Bean
public ApplicationRunner applicationRunner(final Environment environment,
                                           final ServerSchedulerService serverSchedulerService) {
    return args -> {
        final SchedulerConfiguration schedulerConfiguration = new SchedulerConfiguration();
        schedulerConfiguration.setApplication(environment.getProperty("spring.application.name"));
        schedulerConfiguration.setJobName("simpleJob");
        schedulerConfiguration.setMaxRetries(3);
        schedulerConfiguration.setInstanceExecutionCount(1);
        schedulerConfiguration.setRetryable(Boolean.TRUE);
        schedulerConfiguration.setCronExpression("0/30 * * * * ?");
        schedulerConfiguration.setJobIncrementer(JobIncrementer.DATE);
        schedulerConfiguration.setStatus(ServerSchedulerStatus.ACTIVE);
        final Map<String, Object> jobParameters = new HashMap<>();
        jobParameters.put("my-long-value", 200L);
        jobParameters.put("my-string", "hello");
        schedulerConfiguration.setJobParameters(jobParameters);

        serverSchedulerService.initSchedulerExecution(schedulerConfiguration);


    };
}
 
Example #2
Source File: ClusterConfigurationWithAuthenticationIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Bean
ApplicationRunner peerCacheVerifier(GemFireCache cache) {

	return args -> {

		assertThat(cache).isNotNull();
		assertThat(GemfireUtils.isPeer(cache)).isTrue();
		assertThat(cache.getName())
			.isEqualTo(ClusterConfigurationWithAuthenticationIntegrationTests.class.getSimpleName());

		List<String> regionNames = cache.rootRegions().stream()
			.map(Region::getName)
			.collect(Collectors.toList());

		assertThat(regionNames)
			.describedAs("Expected no Regions; but was [%s]", regionNames)
			.isEmpty();
	};
}
 
Example #3
Source File: DubboSpringCloudConsumerBootstrap.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Bean
public ApplicationRunner userServiceRunner() {
	return arguments -> {

		User user = new User();
		user.setId(1L);
		user.setName("小马哥");
		user.setAge(33);

		// save User
		System.out.printf("UserService.save(%s) : %s\n", user,
				userService.save(user));

		// find all Users
		System.out.printf("UserService.findAll() : %s\n", user,
				userService.findAll());

		// remove User
		System.out.printf("UserService.remove(%d) : %s\n", user.getId(),
				userService.remove(user.getId()));

	};
}
 
Example #4
Source File: SpringBootApacheGeodeClientCacheApplication.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Bean
ApplicationRunner applicationAssertionRunner(ConfigurableApplicationContext applicationContext) {

	return args -> {

		Assert.notNull(applicationContext, "ApplicationContext is required");

		Environment environment = applicationContext.getEnvironment();

		Assert.notNull(environment, "Environment is required");
		Assert.isTrue(ArrayUtils.isEmpty(ArrayUtils.nullSafeArray(environment.getActiveProfiles(), String.class)),
			"Expected Active Profiles to be empty");
		Assert.isTrue(Arrays.asList(ArrayUtils.nullSafeArray(environment.getDefaultProfiles(), String.class))
				.contains("default"), "Expected Default Profiles to contain 'default'");

		ClientCache clientCache = applicationContext.getBean(ClientCache.class);

		Assert.notNull(clientCache, "ClientCache is expected");
		Assert.isTrue(SpringBootApacheGeodeClientCacheApplication.class.getSimpleName().equals(clientCache.getName()),
			"ClientCache.name is not correct");

		this.logger.info("Application assertions successful!");
	};
}
 
Example #5
Source File: SpringBoot2IntroApplication.java    From Spring-Boot-2.0-Projects with MIT License 6 votes vote down vote up
@Bean
public ApplicationRunner runner(DemoApplicationProperties myApplicationProperties, Environment environment) {
	return args -> {

		List<Address> addresses = Binder.get(environment)
				.bind("demo.addresses", Bindable.listOf(Address.class))
				.orElseThrow(IllegalStateException::new);

		System.out.printf("Demo Addresses : %s\n", addresses);

		// DEMO_ENV_1 Environment Variable
		System.out.printf("Demo Env 1 : %s\n", environment.getProperty("demo.env[1]"));

		System.out.printf("Demo First Name : %s\n", myApplicationProperties.getFirstName());
		System.out.printf("Demo Last Name : %s\n", myApplicationProperties.getLastName());
		System.out.printf("Demo Username : %s\n", myApplicationProperties.getUsername());
		System.out.printf("Demo Working Time (Hours) : %s\n", myApplicationProperties.getWorkingTime().toHours());
		System.out.printf("Demo Number : %d\n", myApplicationProperties.getNumber());
		System.out.printf("Demo Telephone Number : %s\n", myApplicationProperties.getTelephoneNumber());
		System.out.printf("Demo Email 1 : %s\n", myApplicationProperties.getEmailAddresses().get(0));
		System.out.printf("Demo Email 2 : %s\n", myApplicationProperties.getEmailAddresses().get(1));
	};
}
 
Example #6
Source File: SpringBoot2TaxiServiceApplication.java    From Spring-Boot-2.0-Projects with MIT License 6 votes vote down vote up
@Bean
public ApplicationRunner applicationRunner(TaxiRepository taxiRepository, TaxiService taxiService) {
	return args -> {
		taxiRepository.deleteAll();

		taxiRepository.save(new Taxi(UUID.randomUUID().toString(), TaxiType.MINI, TaxiStatus.AVAILABLE));
		taxiRepository.save(new Taxi(UUID.randomUUID().toString(), TaxiType.NANO, TaxiStatus.AVAILABLE));
		taxiRepository.save(new Taxi(UUID.randomUUID().toString(), TaxiType.VAN, TaxiStatus.AVAILABLE));

		Iterable<Taxi> taxis = taxiRepository.findAll();

		taxis.forEach(t -> {
			taxiService.updateLocation(t.getTaxiId(), LocationGenerator.getLocation(79.865072, 6.927610, 3000)).subscribe();
		});
	};
}
 
Example #7
Source File: EventServer.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
@Bean
public ApplicationRunner runner(CustomerRepository customerRepository, OrderRepository orderRepository,
		ProductRepository productRepository, OrderProductSummaryRepository orderProductSummaryRepository,
		@Qualifier("Products") Region<Long, Product> products) {
	return args -> {
		createCustomerData(customerRepository);

		createProducts(productRepository);

		createOrders(productRepository, orderRepository);

		log.info("Completed creating orders ");

		List<OrderProductSummary> allForProductID = orderProductSummaryRepository.findAllForProductID(3L);
		allForProductID.forEach(orderProductSummary -> log.info("orderProductSummary = " + orderProductSummary));
	};
}
 
Example #8
Source File: WebfluxDemo.java    From spring-five-functional-reactive with Apache License 2.0 6 votes vote down vote up
/**
 * Application runner to initialize a capped collection for {@link Event}s and insert a new {@link Event} every two
 * seconds.
 * 
 * @param operations
 * @param reactiveOperations
 * @return
 */
@Bean
ApplicationRunner onStart(MongoOperations operations, ReactiveMongoOperations reactiveOperations) {

	return args -> {

		CollectionOptions options = CollectionOptions.empty() //
				.capped() //
				.size(2048) //
				.maxDocuments(1000);

		operations.dropCollection(Event.class);
		operations.createCollection(Event.class, options);

		Flux.interval(Duration.ofSeconds(2)) //
				.map(counter -> new Event(LocalDateTime.now())) //
				.flatMap(reactiveOperations::save) //
				.log() //
				.subscribe();
	};
}
 
Example #9
Source File: MultipleDataModuleExample.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Bean
ApplicationRunner applicationRunner() {
	return (args) -> {

		System.out.println("Deleting all entities.");

		this.personRepository.deleteAll();
		this.traderRepository.deleteAll();

		System.out.println("The number of Person entities is now: " + this.personRepository.count());
		System.out.println("The number of Trader entities is now: " + this.traderRepository.count());

		System.out.println("Saving one entity with each repository.");

		this.traderRepository.save(new Trader("id1", "trader", "one"));
		this.personRepository.save(new Person(1L, "person1"));

		System.out.println("The number of Person entities is now: " + this.personRepository.count());
		System.out.println("The number of Trader entities is now: " + this.traderRepository.count());
	};
}
 
Example #10
Source File: CarServiceApplication.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Bean
ApplicationRunner init(CarRepository repository) {
    // Electric VWs from https://www.vw.com/electric-concepts/
    // Release dates from https://www.motor1.com/features/346407/volkswagen-id-price-on-sale/
    Car ID = new Car(UUID.randomUUID(), "ID.", LocalDate.of(2019, Month.DECEMBER, 1));
    Car ID_CROZZ = new Car(UUID.randomUUID(), "ID. CROZZ", LocalDate.of(2021, Month.MAY, 1));
    Car ID_VIZZION = new Car(UUID.randomUUID(), "ID. VIZZION", LocalDate.of(2021, Month.DECEMBER, 1));
    Car ID_BUZZ = new Car(UUID.randomUUID(), "ID. BUZZ", LocalDate.of(2021, Month.DECEMBER, 1));
    Set<Car> vwConcepts = Set.of(ID, ID_BUZZ, ID_CROZZ, ID_VIZZION);

    return args -> {
        repository
                .deleteAll()
                .thenMany(
                        Flux
                                .just(vwConcepts)
                                .flatMap(repository::saveAll)
                )
                .thenMany(repository.findAll())
                .subscribe(car -> log.info("saving " + car.toString()));
    };
}
 
Example #11
Source File: BaseAdminApplication.java    From base-admin with MIT License 6 votes vote down vote up
/**
 * 启动成功
 */
@Bean
public ApplicationRunner applicationRunner() {
    return applicationArguments -> {
        try {
            //系统启动时获取数据库数据,设置到公用静态集合sysSettingMap
            SysSettingVo sysSettingVo = sysSettingService.get("1").getData();
            sysSettingVo.setUserInitPassword(null);//隐藏部分属性
            SysSettingUtil.setSysSettingMap(sysSettingVo);

            //获取本机内网IP
            log.info("启动成功:" + "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + port + "/");
        } catch (UnknownHostException e) {
            //输出到日志文件中
            log.error(ErrorUtil.errorInfoToString(e));
        }
    };
}
 
Example #12
Source File: SpringbootAsyncApplication.java    From springBoot with MIT License 6 votes vote down vote up
/**
     * 启动成功
     */
    @Bean
    public ApplicationRunner applicationRunner() {
        return applicationArguments -> {
            long startTime = System.currentTimeMillis();
            System.out.println(Thread.currentThread().getName() + ":开始调用异步业务");
            //无返回值
//            testService.asyncTask();

            //有返回值,但主线程不需要用到返回值
//            Future<String> future = testService.asyncTask("huanzi-qch");
            //有返回值,且主线程需要用到返回值
//            System.out.println(Thread.currentThread().getName() + ":返回值:" + testService.asyncTask("huanzi-qch").get());

            //事务测试,事务正常提交
//            testService.asyncTaskForTransaction(false);
            //事务测试,模拟异常事务回滚
//            testService.asyncTaskForTransaction(true);

            long endTime = System.currentTimeMillis();
            System.out.println(Thread.currentThread().getName() + ":调用异步业务结束,耗时:" + (endTime - startTime));
        };
    }
 
Example #13
Source File: SpannerExampleDriver.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Bean
@Profile("!test")
ApplicationRunner applicationRunner() {
	return (args) -> {
		if (!args.containsOption("spanner_repository") && !args.containsOption("spanner_template")) {
			throw new IllegalArgumentException("To run the Spanner example, please specify "
					+ " -Dspring-boot.run.arguments=--spanner_repository to run the Spanner repository"
					+ " example or -Dspring-boot.run.arguments=--spanner_template to"
					+ " run the Spanner template example.");
		}

		if (args.containsOption("spanner_repository")) {
			LOGGER.info("Running the Spanner Repository Example.");
			this.spannerRepositoryExample.runExample();
		}
		else if (args.containsOption("spanner_template")) {
			LOGGER.info("Running the Spanner Template Example.");
			this.spannerTemplateExample.runExample();
		}
	};
}
 
Example #14
Source File: BootGeodeNearCachingClientCacheApplication.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Bean
public ApplicationRunner runner(@Qualifier("YellowPages") Region<String, Person> yellowPages) {

	return args -> {

		assertThat(yellowPages).isNotNull();
		assertThat(yellowPages.getName()).isEqualTo("YellowPages");
		assertThat(yellowPages.getInterestListRegex()).containsAnyOf(".*");
		assertThat(yellowPages.getAttributes()).isNotNull();
		assertThat(yellowPages.getAttributes().getDataPolicy()).isEqualTo(DataPolicy.NORMAL);
		assertThat(yellowPages.getAttributes().getPoolName()).isEqualTo("DEFAULT");

		Pool defaultPool = PoolManager.find("DEFAULT");

		assertThat(defaultPool).isNotNull();
		assertThat(defaultPool.getSubscriptionEnabled()).isTrue();

	};
}
 
Example #15
Source File: SpringBootApacheGeodePeerCacheApplication.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Bean
public ApplicationRunner peerCacheAssertRunner(Cache peerCache) {

	return args -> {

		assertThat(peerCache).isNotNull();
		assertThat(peerCache.getName()).isEqualTo(SpringBootApacheGeodePeerCacheApplication.class.getSimpleName());
		assertThat(peerCache.getDistributedSystem()).isNotNull();
		assertThat(peerCache.getDistributedSystem().getProperties()).isNotNull();
		assertThat(peerCache.getDistributedSystem().getProperties().getProperty("disable-auto-reconnect"))
			.isEqualTo("false");
		assertThat(peerCache.getDistributedSystem().getProperties().getProperty("use-cluster-configuration"))
			.isEqualTo("true");

		this.logger.info("Peer Cache [{}] configured and bootstrapped successfully!", peerCache.getName());
		//System.err.printf("Peer Cache [%s] configured and bootstrapped successfully!%n", peerCache.getName());
	};
}
 
Example #16
Source File: GeodeCacheServerHealthIndicatorAutoConfigurationIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Bean
ApplicationRunner runner(ServerLoadProbe mockServerLoadProbe,
		@Qualifier("MockCacheServer") CacheServer mockCacheServer) {

	return args -> {

		assertThat(mockCacheServer.getLoadProbe()).isInstanceOf(ActuatorServerLoadProbeWrapper.class);

		ServerMetrics mockServerMetrics = CacheServerMockObjects.mockServerMetrics(21,
			400, 800, 200);

		ServerLoad mockServerLoad = CacheServerMockObjects.mockServerLoad(0.65f,
			0.35f, 0.75f, 0.55f);

		when(mockServerLoadProbe.getLoad(eq(mockServerMetrics))).thenReturn(mockServerLoad);

		ServerLoadProbe serverLoadProbe = mockCacheServer.getLoadProbe();

		if (serverLoadProbe != null) {
			serverLoadProbe.getLoad(mockServerMetrics);
		}
	};
}
 
Example #17
Source File: BootGeodeNearCachingCacheServerApplication.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Bean
ApplicationRunner runner(@Qualifier("YellowPages") Region<String, Person> yellowPages) {

	return args -> {

		assertThat(yellowPages).isNotNull();
		assertThat(yellowPages.getName()).isEqualTo("YellowPages");
		assertThat(yellowPages.getAttributes()).isNotNull();
		assertThat(yellowPages.getAttributes().getDataPolicy()).isEqualTo(DataPolicy.REPLICATE);
		assertThat(yellowPages.getAttributes().getEnableSubscriptionConflation()).isTrue();

	};
}
 
Example #18
Source File: ReservationServiceApplication.java    From bootiful-reactive-microservices with Apache License 2.0 5 votes vote down vote up
@Bean
ApplicationRunner run(ReservationRepository rr) {
		return args ->
			rr
				.deleteAll()
				.thenMany(Flux.just("[email protected]", "[email protected]", "[email protected]", "[email protected]")
					.map(x -> new Reservation(null, x))
					.flatMap(rr::save))
				.thenMany(rr.findAll())
				.subscribe(System.out::println);
}
 
Example #19
Source File: DemoApplication.java    From spring-cloud-gcp-guestbook with Apache License 2.0 5 votes vote down vote up
@Bean
public ApplicationRunner cli(PubSubTemplate pubSubTemplate) {
	return (args) -> {
		pubSubTemplate.subscribe("messages-subscription-1", 
			(msg) -> { 
				System.out.println(msg.getPubsubMessage()
					.getData().toStringUtf8());
				msg.ack();
			});
	};
}
 
Example #20
Source File: DemoApplication.java    From spring-cloud-gcp-guestbook with Apache License 2.0 5 votes vote down vote up
@Bean
public ApplicationRunner cli(PubSubTemplate pubSubTemplate) {
	return (args) -> {
		pubSubTemplate.subscribe("messages-subscription-1", 
			(msg) -> { 
				System.out.println(msg.getPubsubMessage()
					.getData().toStringUtf8());
				msg.ack();
			});
	};
}
 
Example #21
Source File: CustomRepositoriesApplication.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@Bean
ApplicationRunner runner(CarRepository repository) {
    return args -> {
        Stream.of("A", "B", "C", "D").forEach(carModel -> repository.save(new Car(null, carModel)));
        repository.findAll().forEach(System.out::println);
        repository.doSomethingWith(repository.findOne(1L));
    };
}
 
Example #22
Source File: FluxSinkApplication.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean
ApplicationRunner handler(final Flux<ServerSentEvent<Map>> processor,
                          final Consumer<ServerSentEvent<Map>> onNextConsumer,
                          final Consumer<Throwable> onErrorConsumer,
                          final Runnable completeConsumer) {

  return args -> processor.subscribe(
      onNextConsumer,
      onErrorConsumer,
      completeConsumer
  );
}
 
Example #23
Source File: NacosConfigServerBootstrap.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Bean
public ApplicationRunner applicationRunner() {

	return args -> {
		System.out.println("Running...");
	};
}
 
Example #24
Source File: BootGeodeMultiSiteCachingServerApplication.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Bean
ApplicationRunner geodeClusterObjectsBootstrappedAssertionRunner(Environment environment, Cache cache,
		Region<?, ?> customersByName, GatewayReceiver gatewayReceiver, GatewaySender gatewaySender) {

	return args -> {

		assertThat(cache).isNotNull();
		assertThat(cache.getName()).startsWith(BootGeodeMultiSiteCachingServerApplication.class.getSimpleName());
		assertThat(customersByName).isNotNull();
		assertThat(customersByName.getAttributes()).isNotNull();
		assertThat(customersByName.getAttributes().getDataPolicy()).isEqualTo(DataPolicy.REPLICATE);
		assertThat(customersByName.getAttributes().getGatewaySenderIds()).containsExactly(gatewaySender.getId());
		assertThat(customersByName.getName()).isEqualTo(CUSTOMERS_BY_NAME_REGION);
		assertThat(customersByName.getRegionService()).isEqualTo(cache);
		assertThat(cache.getRegion(RegionUtils.toRegionPath(CUSTOMERS_BY_NAME_REGION))).isEqualTo(customersByName);
		assertThat(gatewayReceiver).isNotNull();
		assertThat(gatewayReceiver.isRunning()).isTrue();
		assertThat(cache.getGatewayReceivers()).containsExactly(gatewayReceiver);
		assertThat(gatewaySender).isNotNull();
		assertThat(gatewaySender.isRunning()).isTrue();
		assertThat(cache.getGatewaySenders().stream().map(GatewaySender::getId).collect(Collectors.toSet()))
			.containsExactly(gatewaySender.getId());

		System.err.printf("Apache Geode Cluster [%s] configured and bootstrapped successfully!%n",
			environment.getProperty("spring.application.name", "UNKNOWN"));
	};
}
 
Example #25
Source File: CacheDataExportAutoConfigurationIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Bean
ApplicationRunner runner(GemfireTemplate golfersTemplate) {

	return args -> {

		save(golfersTemplate, Golfer.newGolfer(1L, "John Blum").withHandicap(9));
		save(golfersTemplate, Golfer.newGolfer(2L, "Moe Haroon").withHandicap(10));

		log("FORE!");
	};
}
 
Example #26
Source File: ApacheGeodeLoggingApplication.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Bean
ApplicationRunner runner() {

	return args -> {

		this.logger.info("RUNNER RAN!");
		this.logger.debug("DEBUG TEST");

		if (ENABLE_PRINT_LOG) {
			printLog();
		}

	};
}
 
Example #27
Source File: AbstractSpringConfiguredLogLevelPropertyIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Bean
ApplicationRunner runner() {
	return args -> {
		logger.debug("DEBUG TEST");
		logger.trace("TRACE TEST");
	};
}
 
Example #28
Source File: ApplicationRunnerListener.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 * @param commandLine The command line
 * @param commandLineRunnerList The command runner list
 * @param applicationRunnerList The application runner list
 */
protected ApplicationRunnerListener(
        CommandLine commandLine,
        List<CommandLineRunner> commandLineRunnerList,
        List<ApplicationRunner> applicationRunnerList) {
    this.commandLine = commandLine;
    this.commandLineRunnerList = commandLineRunnerList;
    this.applicationRunnerList = applicationRunnerList;
}
 
Example #29
Source File: ReservationServiceApplication.java    From training with Apache License 2.0 5 votes vote down vote up
@Bean
ApplicationRunner run(ReservationRepository rr) {
	return args ->
			rr
					.deleteAll()
					.thenMany(Flux.just("Josh", "Kenny", "Dave", "Madhura", "Tasha", "Mario", "Jennifer", "Tammie")
							.map(name -> new Reservation(null, name))
							.flatMap(rr::save))
					.thenMany(rr.findAll())
					.subscribe(System.out::println);
}
 
Example #30
Source File: ReservationServiceApplication.java    From training with Apache License 2.0 5 votes vote down vote up
@Bean
ApplicationRunner run(ReservationRepository rr) {
	return args ->
			rr
					.deleteAll()
					.thenMany(Flux.just("Josh", "Kenny", "Dave", "Madhura", "Tasha", "Mario", "Jennifer", "Tammie")
							.map(name -> new Reservation(null, name))
							.flatMap(rr::save))
					.thenMany(rr.findAll())
					.subscribe(System.out::println);
}