在Spring Boot主方法中直接调用Service可以通过以下步骤完成:

  1. 创建Spring Boot应用程序,并将Service注入到主方法中。

  2. 在主方法中创建Service对象实例,并调用Service方法。

以下是示例代码:

@SpringBootApplication
public class MyApplication {

    @Autowired
    private MyService myService;

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

    @PostConstruct
    public void init() {
        myService.doSomething();
    }

}

在上面的示例中,我们注入了一个MyService对象,并在init()方法中调用了它的doSomething()方法。

请注意,我们使用了@PostConstruct注释来确保在应用程序启动后调用init()方法。如果没有这个注释,可能会发生空指针异常。

希望这可以帮助你


原文地址: https://www.cveoy.top/t/topic/fF2f 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录