SpringBoot2.0-快速入门
一. pom文件引入依赖
pom.xml文件如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
</properties
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
二. 编写Controller层
@RestController
@Slf4j
public class IndexController {
@RequestMapping("/index")
public String index() {
return "Hello, SpringBoot2.1.3";
}
}
三. @RestController
在Controller类上加上RestController 表示修饰该Controller所有的方法返回JSON格式,直接可以编写Restful接口。
四. @EnableAutoConfiguration
注解:作用在于让 Spring Boot 根据应用所声明的依赖来对 Spring 框架进行自动配置
这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。
五. 启动方式
1. 方式一
Springboot默认端口号为8080
@RestController
@EnableAutoConfiguration
public class IndexController {
@RequestMapping("/index")
public String index() {
return "Hello, SpringBoot2.1.3";
}
public static void main(String[] args) {
SpringApplication.run(IndexController .class, args);
}
}
2. 方式二
@ComponentScan(basePackages = "com.springboot.hejr.springboot_helloworld.controller")
@EnableAutoConfiguration
public class SpringbootHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloworldApplication.class, args);
}
}
3. 方式三
@SpringBootApplication 被 @Configuration、@EnableAutoConfiguration、@ComponentScan 注解所修饰,换言之 Springboot 提供了统一的注解来替代以上三个注解
扫包范围:在启动类上加上@SpringBootApplication注解,当前包下或者子包下所有的类都可以扫到。
@SpringBootApplication
public class SpringbootHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloworldApplication.class, args);
}
}