SpringBoot学习笔记-02 SpringBoot开发web

本文介绍了如何将SpringBoot项目从纯Java应用转变为Web项目,通过引入spring-boot-starter-web依赖来启用SpringMVC和内嵌Tomcat。详细步骤包括修改依赖、将配置类注解为@Controller以及实现 CommandLineRunner 接口。启动项目时,SpringBoot会根据依赖启动SpringIoC容器和内嵌Tomcat,提供web服务。
摘要由CSDN通过智能技术生成

我们在01中的SpringBoot项目,在配置类的main方法结束后,项目也就终止了,因为刚刚的开发模式是纯java的,底层使用的是Spring。然而SpringBoot内部集成了Tomcat,可以让我们用来进行web开发, 现在我们来看看:

1. 依赖变动

我们需要让项目变为web项目,就需要改变启动器的底层依赖为SpringMVC。

Spring做底层:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

SpringMVC做底层:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2. 将配置类注解为Controller(真正开发时会分层处理)

package com.zzt;

import com.zzt.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    @Autowired
    private StudentService studentService;

    public static void main(String[] args) {
        ApplicationContext ctx = new SpringApplicationBuilder().sources(DemoApplication.class).
                bannerMode(Banner.Mode.CONSOLE)
                .run();
        StudentService bean = ctx.getBean(StudentService.class);
        System.out.println(bean);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Spring容器构建完成......" + studentService);
    }

    @RequestMapping("/test")
    public @ResponseBody String test(){
        return "Spring Boot Test";
    }
}

3.项目启动

SpringBoot项目启动,run方法判断当前执行的项目类型:

    1. none :纯java项目 --> 启动Spring IoC容器

    2. servlet:web项目  -->  1、启动Spring IoC容器  2、启动内嵌的Tomcat

4.web配置

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值