类org.springframework.boot.ApplicationRunner源码实例Demo

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

源代码1 项目: springBoot   文件: SpringbootAsyncApplication.java
/**
     * 启动成功
     */
    @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));
        };
    }
 
源代码2 项目: base-admin   文件: BaseAdminApplication.java
/**
 * 启动成功
 */
@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));
        }
    };
}
 
@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()));
    };
}
 
@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();
		});
	};
}
 
@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));
	};
}
 
/**
 * 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();
	};
}
 
@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()));

	};
}
 
@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());
	};
}
 
源代码9 项目: spring-cloud-gcp   文件: SpannerExampleDriver.java
@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();
		}
	};
}
 
@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();

	};
}
 
@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();
	};
}
 
@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!");
	};
}
 
@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());
	};
}
 
@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);
		}
	};
}
 
@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);


    };
}
 
源代码16 项目: spring-data-examples   文件: EventServer.java
@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));
	};
}
 
源代码17 项目: data-highway   文件: HighwayPatrolApp.java
@Bean
public ApplicationRunner runner(Receiver receiver, Sender sender) {
  return args -> {
    receiver.start();
    sender.start();
  };
}
 
源代码18 项目: Java-Coding-Problems   文件: MainApplication.java
@Bean
public ApplicationRunner init() {

    return args -> {

        URI uri1 = URI.create("http://localhost:8080/books?name="
                + URLEncoder.encode("Games & Fun!", StandardCharsets.UTF_8)
                + "&no=" + URLEncoder.encode("124#442#000", StandardCharsets.UTF_8)
                + "&price=" + URLEncoder.encode("$23.99", StandardCharsets.UTF_8)
        );

        System.out.println("URI 1: " + uri1);

        URI uri2 = UriComponentsBuilder.newInstance()
                .scheme("http")
                .host("localhost")
                .port(8080)
                .path("books")
                .queryParam("name", "Games & Fun!")
                .queryParam("no", "124#442#000")
                .queryParam("price", "$23.99")
                .build()
                .toUri();

        System.out.println("URI 2: " + uri2);

        URI uri3 = UrlBuilder.empty()
                .withScheme("http")
                .withHost("localhost")
                .withPort(8080)
                .withPath("books")
                .addParameter("name", "Games & Fun!")
                .addParameter("no", "124#442#000")
                .addParameter("price", "$23.99")
                .toUri();
        
        System.out.println("URI 3: " + uri3);
    };
}
 
@Bean
ApplicationRunner runner(DatabaseClient dbc, ReservationRepository reservationRepository) {
	return args -> {

		dbc.execute("create table reservation\n" + "(\n" + "    id   serial primary key,\n"
				+ "    name varchar(255) not null\n" + ")").fetch().rowsUpdated().subscribe();

		reservationRepository.save(new Reservation(null, "Andy")).subscribe();
		reservationRepository.save(new Reservation(null, "Sebastien")).subscribe();

		reservationRepository.findAll().subscribe(System.out::println);
		;
	};
}
 
源代码20 项目: springBoot   文件: SpringbootLogbackApplication.java
/**
 * 启动成功
 */
@Bean
public ApplicationRunner applicationRunner() {
    return applicationArguments -> {
        try {
            InetAddress ia = InetAddress.getLocalHost();
            //获取本机内网IP
            log.info("启动成功:" + "http://" + ia.getHostAddress() + ":" + port + "/");
            logger.info("${user.home} :" + userName);
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        }
    };
}
 
@Bean
ApplicationRunner init(CarRepository repository) {
    return args -> {
        Stream.of("Ferrari", "Jaguar", "Porsche", "Lamborghini", "Bugatti",
                "AMC Gremlin", "Triumph Stag", "Ford Pinto", "Yugo GV").forEach(name -> {
            Car car = new Car();
            car.setName(name);
            repository.save(car);
        });
        repository.findAll().forEach(System.out::println);
    };
}
 
@Bean
public ApplicationRunner run() {
    return new ApplicationRunner() {

        @Autowired
        private SpringPluginManager springPluginManager;

        @Override
        public void run(ApplicationArguments args) throws Exception {
            List<PluginInterface> plugins = springPluginManager.getExtensions(PluginInterface.class);
            log.info(String.format("Number of plugins found: %d", plugins.size()));
            plugins.forEach(c -> log.info(c.getClass().getName() + ":" + c.identify()));
        }
    };
}
 
@Bean
public ApplicationRunner initializeConnection(
        RsvpsWebSocketHandler rsvpsWebSocketHandler) {
    return args -> {
        WebSocketClient rsvpsSocketClient = new StandardWebSocketClient();

        rsvpsSocketClient.doHandshake(
                rsvpsWebSocketHandler, MEETUP_RSVPS_ENDPOINT);           
    };
}
 
@Bean
public ApplicationRunner initializeConnection(
    RsvpsWebSocketHandler rsvpsWebSocketHandler) {
       return args -> {
           WebSocketClient rsvpsSocketClient = new StandardWebSocketClient();

           rsvpsSocketClient.doHandshake(
               rsvpsWebSocketHandler, MEETUP_RSVPS_ENDPOINT);           
       };
   }
 
@Bean
public ApplicationRunner initializeConnection(
    RsvpsWebSocketHandler rsvpsWebSocketHandler) {
        return args -> {
            WebSocketClient rsvpsSocketClient = new StandardWebSocketClient();

            rsvpsSocketClient.doHandshake(
                rsvpsWebSocketHandler, MEETUP_RSVPS_ENDPOINT);           
        };
    }
 
@Bean
public ApplicationRunner initializeConnection(HmlHandler hmlHandler,
        RsvpsWebSocketHandler rsvpsWebSocketHandler) {
    return args -> {
      hmlHandler.recoverAfterRestart();
      rsvpsWebSocketHandler.doHandshake();          
    };                
}
 
源代码27 项目: spring-redis-websocket   文件: HerokuRedisConfig.java
@Bean
ApplicationRunner applicationRunner(RedisChatMessageListener redisChatMessageListener) {
	return args -> {
		redisChatMessageListener.subscribeMessageChannelAndPublishOnWebSocket()
			.doOnSubscribe(subscription -> log.info("Redis Listener Started"))
			.doOnError(throwable -> log.error("Error listening to Redis topic.", throwable))
			.doFinally(signalType -> log.info("Stopped Listener. Signal Type: {}", signalType))
			.subscribe();
	};
}
 
源代码28 项目: spring-redis-websocket   文件: RedisConfig.java
@Bean
ApplicationRunner applicationRunner(RedisChatMessageListener redisChatMessageListener) {
	return args -> {
		redisChatMessageListener.subscribeMessageChannelAndPublishOnWebSocket()
			.doOnSubscribe(subscription -> log.info("Redis Listener Started"))
			.doOnError(throwable -> log.error("Error listening to Redis topic.", throwable))
			.doFinally(signalType -> log.info("Stopped Listener. Signal Type: {}", signalType))
			.subscribe();
	};
}
 
@Bean
@Lazy
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) // 将 Bean Scope 调整为原型(prototype)
public ApplicationRunner applicationRunner(ApplicationContext context) {
    return args -> {
        System.out.printf("当前服务端应用上下文 ID 为:%s\n", context.getId());
    };
}
 
@Bean
public ApplicationRunner runner(BeanFactory beanFactory) {
    return args -> {
        System.out.println("当前 helloWorld Bean 实现类为:"
                + beanFactory.getBean("helloWorld").getClass().getName());

        System.out.println("当前 WebConfiguration Bean 实现类为:"
                + beanFactory.getBean(WebConfiguration.class).getClass().getName());
    };
}
 
 类所在包
 同包方法