0

That's a bit silly, but I'm really missing the point here. I have a Spring Boot working app, the main Application class is

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

}

It it is from this https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-mysql-springdatajpa-hibernate great and simple example. It has a controller for http requests which says

@RequestMapping("/create")
  @ResponseBody
  public String create(String email, String name) {
    User user = null;
    try {
      user = new User(email, name);
      userDao.save(user);
    }
    catch (Exception ex) {
      return "Error creating the user: " + ex.toString();
    }
    return "User succesfully created! (id = " + user.getId() + ")";
  }

My question is, how do I use it like my simple local application with some logic in main() mwthod? I tried something like

new UserController().create("test@test.test", "Test User");

but it doesn't work, though I get no errors. I just don't need any http requests/responses.

Bobby
  • 534
  • 3
  • 7
  • 21
  • 1
    Spring Boot is a framework for building Web applications. Why are you using it if you don't need to build a Web application? – yole Feb 25 '18 at 10:19
  • @yole It's not framework dedicated for web services. It can contain one, but there can be Boot applications without web interface like here: https://stackoverflow.com/questions/26105061/spring-boot-without-the-web-server – ctomek Feb 25 '18 at 10:21
  • @Bobby You can remove those web annotations and execute logic in the main method. If you need some beans there you need to refer to application context object in `main` and get those beans by hand. – ctomek Feb 25 '18 at 10:24
  • So, you want to make a command-line application, not a web application, right? Then don't use Controller, RequestMapping, etc., since that is for defining web controllers. Read the documentation: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-create-a-non-web-application – JB Nizet Feb 25 '18 at 10:27

2 Answers2

2

Once your application is running and your UserController() is ready to accept requested if it annotated by @Controller you can call the create method by url ex. localhost:8080/create providing email, name as request parameters

Amir Serry
  • 326
  • 2
  • 13
1

Yes you can create sprint boot command line application.

please add the below method in Application class of spring boot

@Autowired
private UserServiceImpl userServiceImpl;

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext context) {

    return ((String...args) -> {

    /**
     * 
     * Call any methods of service class
     * 
     */ 

     userServiceImpl.create();

    });
} 
Sri
  • 437
  • 1
  • 4
  • 13