Spring Boot非web应用程序的创建方式

发布时间:2023-03-26 16:43:36

Spring Boot是一个全新的框架,其设计目的是简化新的框架Spring应用程序的初始建设和开发过程,Spring Boot框架使java程序员在开发时样板配置不需要定义,这使得Spring Boot很受欢迎。本文介绍了这篇文章Spring boot非web应用程序如何创建问题,解决大家关于的问题Spring Boot在框架中创建web应用程序的问题。

有时有些项目不需要提供web服务,比如跑定时任务的项目,如果都是按照的话web项目启动这个时候会浪费一些资源。为了达到非web运行的效果,就体现出Spring boot非web应用程序创作的作用。

Spring 在boot框架中,创建一个非Web应用程序(纯Java程序),有两种方式:

Spring boot非web应用程序的创建方式一:

创建纯java项目的启动依赖

<!-- Springboot 开发 java 项目的启动依赖 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter</artifactId>
</dependency>

直接在main方根据SpringAplication的法律.run()方法获取返回的Spring容器对象,然后获取业务bean进行调用;

public static void main(String[] args) {
ApplicationContext context =
SpringApplication.run(Application.class, args);
HelloService helloService = 
(HelloService)context.getBean("helloService");
 String hi = helloService.getMessage("springboot main");
 System.out.println(hi);
}

Spring boot非web应用程序的创建方式二:

1Spring CommandLinerunner接口实现booot入口类;

2、run()方法覆盖commandlineruner接口,在run方法中编写具体的处理逻辑;

@Autowired
private HelloService helloService;
@Override
public void run(String... args) throws Exception {
System.out.println("hello world!");
   String ss = helloService.getMessage(aaa111);
   System.out.println(ss);
}

下面是在Spring boot创建了一个非Web应用程序代码(实现了commandlineruner,并覆盖run()方法)

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

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

    public static void main(String[] args) throws Exception {

        SpringApplication.run(SpringBootConsoleApplication.class, args);

    }

    //access command line arguments
    @Override
    public void run(String... args) throws Exception {
        //do something
    }
}

以上就是Spring boot非web应用程序我希望通过本文的介绍,我们能学会创建两种方法Spring 在Boot框架中创建非创建操作web应用程序。Spring Boot致力于成为蓬勃发展的快速应用开发领域的领导者java程序员必须使用的框架,希望你能学到更多Spring Boot视频教程,零基础的新手朋友早日完成SpringBoot框架从入门到实践的过程。

 

 

上一篇 Docker技术是什么
下一篇 最全类型Spring Boot配置文件总结

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题