我们在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