java非web程序框架_Spring Boot非web应用程序的创建方式

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项目的起步依赖

org.springframework.boot

spring-boot-starter

直接在main方法中,根据SpringApplication.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应用程序的创建方式二:

1、Spring boot的入口类实现CommandLineRunner接口;

2、覆盖CommandLineRunner接口的run()方法,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应用程序的代码(实现了CommandLineRunner,并覆盖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框架从入门到实践的过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值