1.写一个controller
package com.controller.Hello;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // @controller+@responseBody
@RequestMapping("/hello")
public class HelloController {
@RequestMapping("/world")
public String sayHi(){
return "hi world!";
}
}
2.写一个启动器
package com.applicationStarter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// 启动类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
3.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springboot</groupId>
<artifactId>springboot</artifactId>
<version>1.0-SNAPSHOT</version>
<!--引入父maven 继承maven项目中所有的配置信息
spring-boot-dependencies管理了springboot应用中的所有依赖版本
所有导入已有依赖不需要写版本号,解决了第三方库中的版本冲突
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.5.RELEASE</version>
</parent>
<dependencies>
<!--场景启动器:不同的场景启动器维护所有应用的依赖,简化开发
spring-boot-starter-web;使用springmvc构建wrb应用,使用tomcat作为默认的嵌入容器
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!--方便打成jar包生成start-class,部署的时候使用-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4.运行
网页端调用localhost:8080/hello/world输出hi world
ps:如果输入不成搜索出来是404证明找不到包路径 启动类上加上
@SpringBootApplication(scanBasePackages = "com.controller.Hello")即可
5.修改指定端口以及路径
在resources下增加application.properties
server.port=8088
server.servlet.context-path=/lee
重新启动访问localhost:8088/lee/hello/world
即可
6.主要元原理:
首先springboot的启动主要是由一个启动器实现
其中重要注解就是
@SpringBootApplication里面以下几个注解实现
@Configuration跟spring.xml配置类的实现
@ ComponentScan相当于<context:component-scan></>扫描包的作用 ps:无basePackage也可以找到相应的地址 因为spring底层在解析配置类,回去解析ComponentScan,其次就读取basePackages属性,没有读取到会将当前配置类的包当成扫描包,所以开发的时候注意将启动器加到底层目录下