下面列出了怎么用org.springframework.boot.CommandLineRunner的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
};
}
@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());
}
};
}
@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();
};
}
@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);
}
};
}
@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());
}
@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));
}
};
}
@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);
}
};
}
@Bean
public CommandLineRunner writeData(FileWriterGateway gateway, Environment env) {
return args -> {
String[] activeProfiles = env.getActiveProfiles();
if (activeProfiles.length > 0) {
String profile = activeProfiles[0];
gateway.writeToFile("simple.txt", "Hello, Spring Integration! (" + profile + ")");
} else {
System.out.println("No active profile set. Should set active profile to one of xmlconfig, javaconfig, or javadsl.");
}
};
}
@Bean
public CommandLineRunner runner() {
return args -> {
Optional<Foo> foo = entities.findById(1L);
if (!foo.isPresent()) {
entities.save(new Foo("Hello"));
}
};
}
@Bean
CommandLineRunner init(final PhotoService photoService) {
return new CommandLineRunner() {
@Override
public void run(String... strings) throws Exception {
photoService.launchPhotoProcess("one", "two", "three");
}
};
}
@Bean
public CommandLineRunner runner(Bar bar) {
return args -> {
System.out.println("Message: " + message);
System.out.println("Bar: " + bar);
System.out.println("Foo: " + bar.getFoo());
};
}
@Bean
public CommandLineRunner sortingDemo(EmployeeRepository employeeRepository) {
return args -> {
// create new employees
List<Employee> list = Arrays.asList(
new Employee("John", "Doe", 45, 8000),
new Employee("Mike", "Hassan", 55, 6500),
new Employee("Emma", "Doe", 35, 4580),
new Employee("Ali", "Obray", 21, 3200),
new Employee("Beanca", "Lee", 21, 3200)
);
employeeRepository.saveAll(list);
// find all users
// Iterable<Employee> emps = employeeRepository.findAll(Sort.by("age", "salary").descending());
// find users by last name
// Sort sort = Sort.by("salary").descending().and(Sort.by("firstName"));
// List<Employee> employees = employeeRepository.findByLastName("Doe", sort);
Sort sort = Sort.by("salary").descending().and(Sort.by("firstName"))
.and(Sort.by("age").descending()).and(Sort.by("lastName").ascending());
List<Employee> employees = employeeRepository.findBySalaryRange(100, 10000, sort);
// omit sorting
Iterable<Employee> emps = employeeRepository.findAll(Sort.unsorted());
// print employees
employees.forEach(emp -> {
System.out.println(emp.toString());
});
};
}
@Bean
public CommandLineRunner startup() {
return args -> {
log.info("**************************************");
log.info(" Configuring with WebClient");
log.info("**************************************");
};
}
@Bean
public CommandLineRunner myCommandLineRunner() {
return args -> {
Flux<String> output = lines();
dumpFluxToStdOut(output);
};
}
@Bean
public CommandLineRunner runner(Bar bar) {
return args -> {
System.out.println("Message: " + message);
System.out.println("Bar: " + bar);
System.out.println("Foo: " + bar.getFoo());
};
}
@Bean
public CommandLineRunner runner(SimpleProperties simpleProperties, NestedProperties nestedProperties) {
return r -> {
log.info(simpleProperties.getA());
log.info(nestedProperties.getA().getB());
};
}
@Bean
public CommandLineRunner startup() {
return args -> {
log.info("**************************************");
log.info(" Configuring with WebClient");
log.info("**************************************");
};
}
@Bean
public CommandLineRunner runner(BookRepository bookRepository) {
return r -> {
// Create a couple of Book
bookRepository.saveAll(Arrays.asList(new Book("Hello Koding 1", new Date()), new Book("Hello Koding 2", new Date())));
// Fetch all
log.info("My books: " + bookRepository.findAll());
};
}
@Test
public void test() {
assertThat(foo).isNotNull();
assertThat(bar).isNotNull();
assertThat(context.getBeanNamesForType(CommandLineRunner.class)).isNotEmpty();
assertThat(foo.getValue()).isEqualTo("Hello");
}
@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));
};
}
@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(",")));
};
}
@Bean
public CommandLineRunner runner(Bar bar) {
return args -> {
System.out.println("Message: " + message);
System.out.println("Bar: " + bar);
System.out.println("Foo: " + bar.getFoo());
};
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Quote quote = restTemplate.getForObject(
"http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
};
}
@Bean
public CommandLineRunner runner() {
return args -> {
EntityManager manager = entities.createEntityManager();
EntityTransaction transaction = manager.getTransaction();
transaction.begin();
Foo foo = manager.find(Foo.class, 1L);
if (foo == null) {
manager.persist(new Foo("Hello"));
}
transaction.commit();
};
}
@Bean
public CommandLineRunner putAnIngredient(TacoCloudClient tacoCloudClient) {
return args -> {
log.info("----------------------- PUT -------------------------");
Ingredient before = tacoCloudClient.getIngredientById("LETC");
log.info("BEFORE: " + before);
tacoCloudClient.updateIngredient(new Ingredient("LETC", "Shredded Lettuce", Ingredient.Type.VEGGIES));
Ingredient after = tacoCloudClient.getIngredientById("LETC");
log.info("AFTER: " + after);
};
}
@Bean
public CommandLineRunner startup() {
return args -> {
log.info("**************************************");
log.info(" Configuring with RestTemplate");
log.info("**************************************");
};
}
@Bean
public CommandLineRunner runner(Bar bar) {
return args -> {
System.out.println("Message: " + message);
System.out.println("Bar: " + bar);
System.out.println("Foo: " + bar.getFoo());
};
}
@Bean
public CommandLineRunner runner(Bar bar) {
return args -> {
System.out.println("Message: " + message);
System.out.println("Bar: " + bar);
System.out.println("Foo: " + bar.getFoo());
};
}
@Bean
public CommandLineRunner commandLineRunner(DependencyProcessor dependencyProcessor, ResourceLoader resourceLoader) {
return args -> {
if (launcherProperties.getApplicationPath() == null) {
throw new LaunchingException("application path can not be null");
}
if (originalMBeanDomain != null) {
System.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, originalMBeanDomain);
}
if (originalAdminEnabled != null) {
System.setProperty("spring.application.admin.enabled", originalAdminEnabled);
}
Resource gitResource = resourceLoader.getResource("classpath:/git.properties");
try (InputStream in = gitResource.getInputStream()) {
Properties props = new Properties();
props.load(in);
props.forEach((key, value) -> {
System.setProperty("formula.launcher." + key, (String) value);
});
} catch (FileNotFoundException e) {
// do nothing
}
new FormulaLauncher(launcherProperties, dependencyProcessor).launch(args);
};
}
@Profile("usage_msg")
@Bean
public CommandLineRunner useage() {
return args -> {
System.out.println("This app uses Spring Profiles to control its behavior.\n");
System.out.println("Sample usage: java -jar target/rabbitmq-samples-0.0.1-SNAPSHOT.jar --springboot.profiles.active=hello-world,sender");
};
}