SpringBoot从零开始实战(二)创建非Web项目

前言

虽然大家伙用Spring Boot一般都做的是Web项目,然而Spring Boot也是可以做普通Java项目的,整个过程与Web项目比较起来比较类似,只是少了跟前端页面的一些东西,剩下的还是一模一样。

1. 搭建环境

与上一章搭建Java Web环境很类似,唯一不同的是选择依赖的时候,什么也不选,其他的保持一样就可以了。
在这里插入图片描述

2. 实现方法

用Spring Boot 开发纯Java项目有两种方式,我们仍旧新建一个HelloService类来调取里面的getHi方法来演示,项目入口类为 Application

import org.springframework.stereotype.Service;
//HelloService类
@Service
public class HelloService {
    
    public String getHi(){
        return "Hello, Spring Boot";
    }
}

2.1 第一种方式:手动获取Spring容器中的Bean

/**
 * 创建非Web项目的第一种方式
 */
@SpringBootApplication
public class Application {

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

}

2.2 第二种方式:继承CommandLineRunner接口,使用自动注入特性

/**
 * 创建非项目的第二种方式
 */
@SpringBootApplication
public class NotwebApplication implements CommandLineRunner{
    @Autowired
    private HelloService helloService;

    public static void main(String[] args) {
        SpringApplication.run(NotwebApplication.class, args);
    }
    
    @Override
    public void run(String[] args) throws Exception {
        String hi = helloService.getHi();
        System.out.println(hi);
    }
}

3. 总结

这里推荐使用第二种方式,毕竟代码量更少,更容易理解。

上一章:SpringBoot从零开始实战(一)配置环境及HelloWorld
下一章:暂无

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值