繁体   English   中英

本地简单项目如何使用Spring boot?

[英]How to use Spring boot for local simple project?

这有点愚蠢,但我真的错过了这里的重点。 我有一个 Spring Boot 工作应用程序,主要的 Application 类是

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);
  }

}

它来自这个https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-mysql-springdatajpa-hibernate伟大而简单的例子。 它有一个用于 http 请求的控制器,上面写着

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

我的问题是,如何像使用 main() mwthod 中的某些逻辑的简单本地应用程序一样使用它? 我试过类似的东西

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

但它不起作用,尽管我没有收到任何错误。 我只是不需要任何 http 请求/响应。

一旦您的应用程序运行并且您的 UserController() 已准备好接受由 @Controller 注释的请求,您可以通过 url ex 调用 create 方法。 localhost:8080/create 提供电子邮件,名称作为请求参数

是的,您可以创建 sprint boot 命令行应用程序。

请在spring boot的Application类中添加以下方法

@Autowired
private UserServiceImpl userServiceImpl;

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext context) {

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

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

     userServiceImpl.create();

    });
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM