@Bean CommandLineRunner init(MongoOperations operations) { return args -> { // tag::log[] operations.dropCollection(Image.class); operations.insert(new Image("1", "learning-spring-boot-cover.jpg")); operations.insert(new Image("2", "learning-spring-boot-2nd-edition-cover.jpg")); operations.insert(new Image("3", "bazinga.png")); operations.findAll(Image.class).forEach(image -> { System.out.println(image.toString()); }); // end::log[] }; }
@Bean public CommandLineRunner runner(GitterProperties props, MongoProperties mongoProperties) { return args -> { context.registerBean(Mate.class, () -> new Mate("Lithium", "Alex", true)); Mate mate = context.getBean(Mate.class); System.out.println("Mate from context: " + mate.nickname); System.out.println("Gitter Room: " + props.getRoom()); Flux<Mate> people = Flux.just( new Mate("aliaksei-lithium", "Aliaksei"), new Mate("IRus", "Ruslan"), new Mate("bsiamionau", "Bahdan") ); repository.deleteAll().thenMany(repository.save(people)).blockLast(); }; }
@Profile("trace") @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return args -> { System.out.println("Let's inspect the beans provided by Spring Boot:\n"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.println(beanName); } System.out.println("---"); }; }
/** * Pre-load some test images * * @return Spring Boot {@link CommandLineRunner} automatically * run after app context is loaded. */ @Bean CommandLineRunner setUp() throws IOException { return (args) -> { FileSystemUtils.deleteRecursively(new File(UPLOAD_ROOT)); Files.createDirectory(Paths.get(UPLOAD_ROOT)); FileCopyUtils.copy("Test file", new FileWriter(UPLOAD_ROOT + "/learning-spring-boot-cover.jpg")); FileCopyUtils.copy("Test file2", new FileWriter(UPLOAD_ROOT + "/learning-spring-boot-2nd-edition-cover.jpg")); FileCopyUtils.copy("Test file3", new FileWriter(UPLOAD_ROOT + "/bazinga.png")); }; }
@Bean CommandLineRunner init(MongoOperations operations) { return args -> { // tag::log[] operations.dropCollection(Image.class); operations.insert(new Image("1", "learning-spring-boot-cover.jpg", "greg")); operations.insert(new Image("2", "learning-spring-boot-2nd-edition-cover.jpg", "greg")); operations.insert(new Image("3", "bazinga.png", "phil")); operations.findAll(Image.class).forEach(image -> { System.out.println(image.toString()); }); // end::log[] }; }
@Bean CommandLineRunner initializeUsers(MongoOperations operations) { return args -> { operations.dropCollection(User.class); operations.insert( new User( null, "greg", "turnquist", new String[]{"ROLE_USER", "ROLE_ADMIN"})); operations.insert( new User( null, "phil", "webb", new String[]{"ROLE_USER"})); operations.findAll(User.class).forEach(user -> { System.out.println("Loaded " + user); }); }; }
/** * Pre-load some fake images * * @return Spring Boot {@link CommandLineRunner} automatically run after app context is loaded. */ @Bean CommandLineRunner setUp() throws IOException { return (args) -> { FileSystemUtils.deleteRecursively(new File(UPLOAD_ROOT)); Files.createDirectory(Paths.get(UPLOAD_ROOT)); FileCopyUtils.copy("Test file", new FileWriter(UPLOAD_ROOT + "/learning-spring-boot-cover.jpg")); FileCopyUtils.copy("Test file2", new FileWriter(UPLOAD_ROOT + "/learning-spring-boot-2nd-edition-cover.jpg")); FileCopyUtils.copy("Test file3", new FileWriter(UPLOAD_ROOT + "/bazinga.png")); }; }
@Bean CommandLineRunner init(MongoOperations operations) { return args -> { operations.dropCollection(Image.class); operations.insert(new Image("1", "learning-spring-boot-cover.jpg")); operations.insert(new Image("2", "learning-spring-boot-2nd-edition-cover.jpg")); operations.insert(new Image("3", "bazinga.png")); operations.findAll(Image.class).forEach(image -> { System.out.println(image.toString()); }); }; }
@Bean public CommandLineRunner demo(NoteRepository repository) { return (args) -> { // save a couple of notes repository.save(new NoteEntity("Spring Boot", "Need to implement REST Services")); repository.save(new NoteEntity("Learn Maven", "Learn the concept of Dependency Mangement")); repository.save(new NoteEntity("ABC", "Bla Bla Bla..")); // fetch all notes log.info("Customers found with findAll():"); log.info("-------------------------------"); for (NoteEntity notes : repository.findAll()) { log.info(notes.toString()); } }; }
@Bean public CommandLineRunner demo(NoteRepository repository) { return (args) -> { // save a couple of notes repository.save(new NoteEntity("Spring Boot", "Setup spring boot application")); repository.save(new NoteEntity("Maven Multi Module", "build a multi module maven project")); repository.save(new NoteEntity("Learn JPA", "Go though basic concepts of JPA")); // fetch all notes log.info("Notes found with findAll():"); log.info("-------------------------------"); for (NoteEntity notes : repository.findAll()) { log.info(notes.toString()); } }; }
@Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return args -> { String[] beanNames = ctx.getBeanDefinitionNames(); System.out.println("********************************************"); // TODO: FIXME: Logger level not working logger.debug("**************************************************"); System.out.println("Listing the "+beanNames.length+" beans loaded by Spring Boot:"); // logger.debug("Listing the {} beans loaded by Spring Boot:", beanNames.length); Arrays.stream(beanNames) .sorted().forEach(System.out::println); logger.debug("*** the End **************************************\n\n"); System.out.println("*** the End ********************************\n\n"); }; }
@Bean CommandLineRunner init( AccountService accountService ) { return (evt) -> Arrays.asList( "user,admin,john,robert,ana".split(",")).forEach( username -> { Account acct = new Account(); acct.setUsername(username); if ( username.equals("user")) acct.setPassword("password"); else acct.setPassword(passwordEncoder().encode("password")); acct.setFirstName(username); acct.setLastName("LastName"); acct.grantAuthority("ROLE_USER"); if ( username.equals("admin") ) acct.grantAuthority("ROLE_ADMIN"); try { accountService.register(acct); } catch (AccountException e) { e.printStackTrace(); } } ); }
@Bean public CommandLineRunner demo(AddressRepository repository) { return (args) -> { repository.save(new Address("DE", "Solingen", "42697", "Hochstraße", "11")); repository.save(new Address("DE", "Berlin", "10785", "Kemperplatz", "1")); repository.save(new Address("DE", "Dortmund", "44137", "Hoher Wall", "15")); repository.save(new Address("DE", "Düsseldorf", "40591", "Kölner Landstraße", "11")); repository.save(new Address("DE", "Frankfurt", "60486", "Kreuznacher Straße", "30")); repository.save(new Address("DE", "Hamburg", "22767", "Große Elbstraße", "14")); repository.save(new Address("DE", "Karlsruhe", "76135", "Gartenstraße", "69a")); repository.save(new Address("DE", "München", "80687", "Elsenheimerstraße", "55a")); repository.save(new Address("DE", "Münster", "48167", "Wolbecker Windmühle", "29j")); repository.save(new Address("DE", "Nürnberg", "90403", "Josephsplatz", "8")); repository.save(new Address("DE", "Stuttgart", "70563", "Curiesstraße", "2")); log.info("### Address count:" + repository.count()); }; }
@Bean CommandLineRunner lineRunner(QuestionRestRepository questionRestRepository) { return (args) -> { Question q = new Question(); q.setContent("1+2"); Answer a1 = new Answer(); a1.setContent("2"); Answer a2 = new Answer(); a2.setContent("3"); a2.setCorrect(true); Answer a3 = new Answer(); a3.setContent("4"); q.getAnswers().add(a1); q.getAnswers().add(a2); q.getAnswers().add(a3); questionRestRepository.save(q); }; }
@Bean public CommandLineRunner run() { return args -> { logger.info("Ajout d'un nouveau document: {} / {} [{}]", newDocumentPath, newDocumentName, newDocumentLocation); final Path location = Paths.get(newDocumentLocation); logger.debug("Le fichier {} {}", location, Files.exists(location) ? "existe" : "n'existe pas"); final AlfredService alfredService = alfredFactory.createAlfredServiceBuilder() .url(alfredUrl) .username(alfredUsername) .password(alfredPassword); final Supplier<NodeReference> createDocumentFromProperties = () -> createDocument(alfredService); final NodeReference nodeReference = alfredService .documentByNodeReference(nodeReferenceAddContent.orElseGet(createDocumentFromProperties)) .content(location) .getNodeReference(); logger.info("Le document {} a été poussé dans Alfresco. Il s'agit du noeud {}", newDocumentName, nodeReference.getNodeReference()); }; }
@Bean CommandLineRunner runner(final ProductRepo productRepo) { return strings -> { final List<Product> products = Arrays.asList( new Product("Notebook Basic 15", "Notebook Basic 15 with 1,7GHz - 15\" XGA - 1024MB DDR2 SDRAM - 40GB Hard Disc", "956.00", "EUR", "images/HT-1000.jpg"), new Product("Notebook Professional 15", "Notebook Professional 15 with 2,3GHz - 15\" XGA - 2048MB DDR2 SDRAM - 40GB Hard Disc - DVD-Writer (DVD-R/+R/-RW/-RAM)", "1999.00", "EUR", "images/HT-1010.jpg"), new Product("Ergo Screen", "17\" Optimum Resolution 1024 x 768 @ 85Hz, Max resolution 1280 x 960 @ 75Hz, Dot Pitch: 0.27mm", "230.00", "EUR", "images/HT-1030.jpg")); productRepo.save(products); productRepo.findAll().forEach(System.out::println); }; }
/** * 初始化系统方法,创建管理员账号admin,创建初始用户角色ROLE_ADMIN,ROLE_USER * * */ @Bean public CommandLineRunner init(AuthorService authorService, RoleService roleService) { return (args) -> { Role role = new Role(); role.setName("ROLE_USER"); roleService.save(role); Role role1 = new Role(); role1.setName("ROLE_ADMIN"); roleService.save(role1); Set<Role> set = new HashSet(); set.add(role); set.add(role1); Author author = new Author(); author.setId(UUID.randomUUID().toString()); author.setUsername("admin"); author.setAuthorities(set); author.setPassword(MD5Tools.md5EncodePassword("admin", author.getUsername())); authorService.save(author); }; }
@Bean CommandLineRunner initDatabase(EmployeeRepository employeeRepository, ManagerRepository managerRepository) { return args -> { /* * Gather Gandalf's team */ Manager gandalf = managerRepository.save(new Manager("Gandalf")); Employee frodo = employeeRepository.save(new Employee("Frodo", "ring bearer", gandalf)); Employee bilbo = employeeRepository.save(new Employee("Bilbo", "burglar", gandalf)); gandalf.setEmployees(Arrays.asList(frodo, bilbo)); managerRepository.save(gandalf); /* * Put together Saruman's team */ Manager saruman = managerRepository.save(new Manager("Saruman")); Employee sam = employeeRepository.save(new Employee("Sam", "gardener", saruman)); saruman.setEmployees(Arrays.asList(sam)); managerRepository.save(saruman); }; }
/** * Bootstrap the Neo4j database with demo dataset. This can run multiple times without * duplicating data. * * @param graphDatabaseConfiguration is the graph database configuration to communicate with the Neo4j server * @return a {@link CommandLineRunner} instance with the method delegate to execute */ @Bean public CommandLineRunner commandLineRunner(GraphDatabaseConfiguration graphDatabaseConfiguration) { return strings -> { if(bootstrap) { logger.info("Creating index on User(id) and Product(id)..."); graphDatabaseConfiguration.neo4jTemplate().query("CREATE INDEX ON :User(id)", null).finish(); graphDatabaseConfiguration.neo4jTemplate().query("CREATE INDEX ON :Product(id)", null).finish(); logger.info("Importing ratings data..."); // Import graph data for movie ratings String userImport = String.format("USING PERIODIC COMMIT 20000\n" + "LOAD CSV WITH HEADERS FROM \"%s/ratings.csv\" AS csvLine\n" + "MERGE (user:User:_User { id: toInt(csvLine.userId) })\n" + "ON CREATE SET user.__type__=\"User\", user.className=\"data.domain.nodes.User\", user.knownId = csvLine.userId\n" + "MERGE (product:Product:_Product { id: toInt(csvLine.movieId) })\n" + "ON CREATE SET product.__type__=\"Product\", product.className=\"data.domain.nodes.Product\", product.knownId = csvLine.movieId\n" + "MERGE (user)-[r:Rating]->(product)\n" + "ON CREATE SET r.timestamp = toInt(csvLine.timestamp), r.rating = toInt(csvLine.rating), r.knownId = csvLine.userId + \"_\" + csvLine.movieId, r.__type__ = \"Rating\", r.className = \"data.domain.rels.Rating\"", datasetUrl); graphDatabaseConfiguration.neo4jTemplate().query(userImport, null).finish(); logger.info("Import complete"); } }; }
@Bean public CommandLineRunner houses(HouseRepository houseRepository) { return args -> { Stream.of(new House("111 8th Av., NYC"), new House("636 Avenue of the Americas, NYC"), new House("White House"), new House("Pentagon")) .forEach(houseRepository::save); houseRepository.findAll().forEach(house -> LOGGER.info(house.getAddress())); }; }