org.springframework.boot.CommandLineRunner Java Examples

The following examples show how to use org.springframework.boot.CommandLineRunner. 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: Application.java    From code-examples with MIT License 7 votes vote down vote up
@Bean
public CommandLineRunner auditingDemo(TodoRepository todoRepository) {
    return args -> {

        // create new todos
        todoRepository.saveAll(Arrays.asList(
                new Todo("Buy milk", false),
                new Todo("Email John", false),
                new Todo("Visit Emma", false),
                new Todo("Call dad", true),
                new Todo("Weekend walk", true),
                new Todo("Write Auditing Tutorial", true)
        ));

        // retrieve all todos
        Iterable<Todo> todos = todoRepository.findAll();

        // print all todos
        todos.forEach(System.out::println);
    };
}
 
Example #2
Source File: TacoCloudApplication.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@Bean
public CommandLineRunner dataLoader(IngredientRepository repo) {
  return new CommandLineRunner() {
    @Override
    public void run(String... args) throws Exception {
      repo.save(new Ingredient("FLTO", "Flour Tortilla", Type.WRAP));
      repo.save(new Ingredient("COTO", "Corn Tortilla", Type.WRAP));
      repo.save(new Ingredient("GRBF", "Ground Beef", Type.PROTEIN));
      repo.save(new Ingredient("CARN", "Carnitas", Type.PROTEIN));
      repo.save(new Ingredient("TMTO", "Diced Tomatoes", Type.VEGGIES));
      repo.save(new Ingredient("LETC", "Lettuce", Type.VEGGIES));
      repo.save(new Ingredient("CHED", "Cheddar", Type.CHEESE));
      repo.save(new Ingredient("JACK", "Monterrey Jack", Type.CHEESE));
      repo.save(new Ingredient("SLSA", "Salsa", Type.SAUCE));
      repo.save(new Ingredient("SRCR", "Sour Cream", Type.SAUCE));
    }
  };
}
 
Example #3
Source File: Application.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Bean
CommandLineRunner init(
        final AnalysingService analysingService,
        final RuntimeService runtimeService) {
    return new CommandLineRunner() {
        @Override
        public void run(String... strings) throws Exception {

            String integrationGatewayProcess = "integrationGatewayProcess";

            runtimeService.startProcessInstanceByKey(
                    integrationGatewayProcess, Collections.singletonMap("customerId", (Object) 232L));


            System.out.println("projectId=" + analysingService.getStringAtomicReference().get());

        }
    };
}
 
Example #4
Source File: SampleRegistrar.java    From spring-init with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
		throws BeansException {
	registry.registerBeanDefinition("foo", BeanDefinitionBuilder
			.genericBeanDefinition(Foo.class, () -> foo()).getBeanDefinition());
	registry.registerBeanDefinition("bar",
			BeanDefinitionBuilder
					.genericBeanDefinition(Bar.class,
							() -> bar(context.getBean(Foo.class)))
					.getBeanDefinition());
	registry.registerBeanDefinition("runner",
			BeanDefinitionBuilder
					.genericBeanDefinition(CommandLineRunner.class,
							() -> runner(context.getBean(Bar.class)))
					.getBeanDefinition());
}
 
Example #5
Source File: Application.java    From spring-data-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
@Bean
public CommandLineRunner rest(ConfigurableApplicationContext ctx, UserRepository dynamoDBRepository,
		AmazonDynamoDB amazonDynamoDB, DynamoDBMapper dynamoDBMapper, DynamoDBMapperConfig config) {
	return (args) -> {

		CreateTableRequest ctr = dynamoDBMapper.generateCreateTableRequest(User.class)
				.withProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
		TableUtils.createTableIfNotExists(amazonDynamoDB, ctr);
		TableUtils.waitUntilActive(amazonDynamoDB, ctr.getTableName());

		createEntities(dynamoDBRepository);

		log.info("");
		log.info("Run curl -v http://localhost:8080/users and follow the HATEOS links");
		log.info("");
		log.info("Press <enter> to shutdown");
		System.in.read();
		ctx.close();
	};
}
 
Example #6
Source File: Application.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Bean
CommandLineRunner customMybatisXmlMapper(final ManagementService managementService) {
    return new CommandLineRunner() {
        @Override
        public void run(String... args) throws Exception {
            String processDefinitionDeploymentId = managementService.executeCommand(new Command<String>() {
                @Override
                public String execute(CommandContext commandContext) {
                    return (String) commandContext
                            .getDbSqlSession()
                            .selectOne("selectProcessDefinitionDeploymentIdByKey", "waiter");
                }
            });

            logger.info("Process definition deployment id = {}", processDefinitionDeploymentId);
        }
    };
}
 
Example #7
Source File: SpringbootMongodbSecurityApplication.java    From springboot-mongodb-security with MIT License 6 votes vote down vote up
@Bean
CommandLineRunner init(RoleRepository roleRepository) {

    return args -> {

        Role adminRole = roleRepository.findByRole("ADMIN");
        if (adminRole == null) {
            Role newAdminRole = new Role();
            newAdminRole.setRole("ADMIN");
            roleRepository.save(newAdminRole);
        }
        
        Role userRole = roleRepository.findByRole("USER");
        if (userRole == null) {
            Role newUserRole = new Role();
            newUserRole.setRole("USER");
            roleRepository.save(newUserRole);
        }
    };

}
 
Example #8
Source File: BarConfiguration.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner runner(Bar bar) {
	return args -> {
		System.out.println("Message: " + message);
		System.out.println("Bar: " + bar);
		System.out.println("Foo: " + bar.getFoo());
	};
}
 
Example #9
Source File: DevelopmentConfig.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner dataLoader(IngredientRepository repo) {
  return args -> {
    repo.save(new Ingredient("FLTO", "Flour Tortilla", Type.WRAP));
    repo.save(new Ingredient("COTO", "Corn Tortilla", Type.WRAP));
    repo.save(new Ingredient("GRBF", "Ground Beef", Type.PROTEIN));
    repo.save(new Ingredient("CARN", "Carnitas", Type.PROTEIN));
    repo.save(new Ingredient("TMTO", "Diced Tomatoes", Type.VEGGIES));
    repo.save(new Ingredient("LETC", "Lettuce", Type.VEGGIES));
    repo.save(new Ingredient("CHED", "Cheddar", Type.CHEESE));
    repo.save(new Ingredient("JACK", "Monterrey Jack", Type.CHEESE));
    repo.save(new Ingredient("SLSA", "Salsa", Type.SAUCE));
    repo.save(new Ingredient("SRCR", "Sour Cream", Type.SAUCE));
  };
}
 
Example #10
Source File: SampleApplicationTests.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
	assertThat(foo).isNotNull();
	assertThat(bar).isNotNull();
	assertThat(context.getBeanNamesForType(CommandLineRunner.class)).isNotEmpty();
	assertThat(foo.getValue()).isEqualTo("Hello");
}
 
Example #11
Source File: SampleApplication.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner runner(Bar bar) {
	return args -> {
		System.out.println("Message: " + message);
		System.out.println("Bar: " + bar);
		System.out.println("Foo: " + bar.getFoo());
	};
}
 
Example #12
Source File: FeignClientConfig.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner startup() {
  return args -> {
    log.info("**************************************");
    log.info("        Configuring with Feign");
    log.info("**************************************");
  };
}
 
Example #13
Source File: RestExamples.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner fetchIngredients(TacoCloudClient tacoCloudClient) {
  return args -> {
    log.info("----------------------- GET -------------------------");
    log.info("GETTING INGREDIENT BY IDE");
    log.info("Ingredient:  " + tacoCloudClient.getIngredientById("CHED"));
    log.info("GETTING ALL INGREDIENTS");
    List<Ingredient> ingredients = tacoCloudClient.getAllIngredients();
    log.info("All ingredients:");
    for (Ingredient ingredient : ingredients) {
      log.info("   - " + ingredient);
    }
  };
}
 
Example #14
Source File: SampleConfiguration.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner runner(ObjectProvider<Bar> bar) {
	return args -> {
		System.out.println("Message: " + message);
		System.out.println("Bar: " + bar.stream().map(v -> v.toString())
				.collect(Collectors.joining(",")));
		System.out.println("Foo: " + bar.stream().map(v -> v.getFoo().toString())
				.collect(Collectors.joining(",")));
	};
}
 
Example #15
Source File: Application.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Bean
CommandLineRunner startProcess(final RuntimeService runtimeService, final TaskService taskService) {
    return new CommandLineRunner() {
        @Override
        public void run(String... strings) throws Exception {
            for (int i = 0; i < 10; i++)
                runtimeService.startProcessInstanceByKey("waiter", Collections.singletonMap("customerId", (Object) i ));

            for (int i=0; i<7; i++)
                taskService.complete(taskService.createTaskQuery().list().get(0).getId());
        }
    };
}
 
Example #16
Source File: RestExamples.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner traversonGetIngredients(TacoCloudClient tacoCloudClient) {
  return args -> {
    Iterable<Ingredient> ingredients = tacoCloudClient.getAllIngredientsWithTraverson();
    log.info("----------------------- GET INGREDIENTS WITH TRAVERSON -------------------------");
    for (Ingredient ingredient : ingredients) {
      log.info("   -  " + ingredient);
    }
  };
}
 
Example #17
Source File: SampleApplication.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Bean
CommandLineRunner clr(Foo f) {
	return args -> {
		System.out.println("Foo: " + f);
		System.out.println("Foo value: " + f.getValue());
	};
}
 
Example #18
Source File: SampleApplication.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner runner(ConfigurableListableBeanFactory beans) {
	return args -> {
		System.err.println("Class count: " + ManagementFactory.getClassLoadingMXBean().getTotalLoadedClassCount());
		System.err.println("Bean count: " + beans.getBeanDefinitionNames().length);
		System.err.println("Bean names: " + Arrays.asList(beans.getBeanDefinitionNames()));
	};
}
 
Example #19
Source File: SampleApplication.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner runner(Bar bar) {
	return args -> {
		System.out.println("Message: " + message);
		System.out.println("Bar: " + bar);
		System.out.println("Foo: " + bar.getFoo());
	};
}
 
Example #20
Source File: SampleApplication.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner runner(ConfigurableListableBeanFactory beans) {
	return args -> {
		System.err.println("Class count: " + ManagementFactory.getClassLoadingMXBean().getTotalLoadedClassCount());
		System.err.println("Bean count: " + beans.getBeanDefinitionNames().length);
		System.err.println("Bean names: " + Arrays.asList(beans.getBeanDefinitionNames()));
	};
}
 
Example #21
Source File: SampleApplication.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner runner(Bar bar) {
	return args -> {
		System.out.println("Message: " + message);
		System.out.println("Bar: " + bar);
		System.out.println("Foo: " + bar.getFoo());
	};
}
 
Example #22
Source File: HttpSimulatorApplication.java    From prom_lab with MIT License 5 votes vote down vote up
@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
	return new CommandLineRunner() {
		public void run(String... args) throws Exception {
			simulator = new ActivitySimulator(opts);
			executor.execute(simulator);
			System.out.println("Simulator thread started...");
		}
	};
}
 
Example #23
Source File: RestExamples.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner fetchIngredients(TacoCloudClient tacoCloudClient) {
  return args -> {
    log.info("----------------------- GET -------------------------");
    log.info("GETTING INGREDIENT BY IDE");
    log.info("Ingredient:  " + tacoCloudClient.getIngredientById("CHED"));
    log.info("GETTING ALL INGREDIENTS");
    List<Ingredient> ingredients = tacoCloudClient.getAllIngredients();
    log.info("All ingredients:");
    for (Ingredient ingredient : ingredients) {
      log.info("   - " + ingredient);
    }
  };
}
 
Example #24
Source File: SampleApplication.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner runner(ConfigurableListableBeanFactory beans) {
	return args -> {
		System.err.println("Class count: " + ManagementFactory.getClassLoadingMXBean().getTotalLoadedClassCount());
		System.err.println("Bean count: " + beans.getBeanDefinitionNames().length);
		System.err.println("Bean names: " + Arrays.asList(beans.getBeanDefinitionNames()));
	};
}
 
Example #25
Source File: BookPubApplication.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
@Bean
public CommandLineRunner configValuePrinter(
        @Value("${my.config.value:}") String configValue) {
    return args ->
            LogFactory.getLog(getClass()).
                    info("Value of my.config.value property is: " + configValue);
}
 
Example #26
Source File: SampleApplication.java    From spring-init with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
		throws BeansException {
	registry.registerBeanDefinition("runner",
			BeanDefinitionBuilder
					.genericBeanDefinition(CommandLineRunner.class,
							() -> runner(context.getBean(Bar.class)))
					.getBeanDefinition());
}
 
Example #27
Source File: BookPubApplication.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
@Bean
public CommandLineRunner configValuePrinter(
        @Value("${my.config.value:}") String configValue) {
    return args ->
            LogFactory.getLog(getClass()).
                    info("Value of my.config.value property is: " + configValue);
}
 
Example #28
Source File: Application.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 5 votes vote down vote up
@Bean
CommandLineRunner init(CustomerRespository customerRepository) {
	return (evt) ->  {
						customerRepository.save(new Customer("Adam","[email protected]"));
						customerRepository.save(new Customer("John","[email protected]"));
						customerRepository.save(new Customer("Smith","[email protected]"));
						customerRepository.save(new Customer("Edgar","[email protected]"));
						customerRepository.save(new Customer("Martin","[email protected]"));
						customerRepository.save(new Customer("Tom","[email protected]"));
						customerRepository.save(new Customer("Sean","[email protected]"));
					};
}
 
Example #29
Source File: Application.java    From boost with Eclipse Public License 1.0 5 votes vote down vote up
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }

    };
}
 
Example #30
Source File: SampleApplication.java    From spring-boot-graal-feature with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner runner() {
	return args -> {
		Optional<Foo> foo = entities.findById(1L);
		if (!foo.isPresent()) {
			entities.save(new Foo("Hello"));
		}
	};
}