SpringBoot study notes-02 SpringBoot development web

In our SpringBoot project in 01, after the main method of the configuration class ends, the project is terminated because the development model just now is pure java, and the bottom layer uses Spring. However, SpringBoot integrates Tomcat internally, which can be used for web development. Now let's take a look:

1. Dependence on changes

We need to make the project a web project, we need to change the underlying dependency of the starter to SpringMVC.

Spring is the bottom layer:

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

SpringMVC does the bottom layer:

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

2. Annotate the configuration class as Controller (it will be processed hierarchically during real development)

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. Project start

The SpringBoot project is started, and the run method determines the type of project currently being executed:

    1. none: pure java project --> start Spring IoC container

    2. servlet: web project --> 1. Start the Spring IoC container 2. Start the embedded Tomcat

4.web configuration

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_39304630/article/details/113074908