Spring Boot入门
SpringBoot优点:
- 快速独立运行Spring项目,以及主流框架集成
- 使用嵌入式Servlet,无需打成war包
- starters自动依赖和版本控制
- 大量自动配置,简化开发,可以修改默认值
- 无需配置XML,无代码生成,开箱即用
- 云计算天然集成
- 准生产环境的运行时应用监控
HelloWorld测试
springboot结构
- static存放静态资源如:js,css,images
- templates:保存所有模板页面
- application.properties: 配置文件
pom.xml
- spring-boot-starter:springboot场景启动器,帮我们导入运行所需模块。
<parent>
<groupId>org.springframework.boot</groupId>
<version>2.3.0.RELEASE</version>
<artifactId>spring-boot-starter-parent</artifactId>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
主程序HelloWorldMainApplication
@SpringBootApplication
@RestController
public class HelloWorldMainApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldMainApplication.class,args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name){
return "Hello "+ name;
}
}
@RestController
包含:@ResponseBody
将方法返回值数据直接写给浏览器,如果是对象转为json对象
或者使用HelloWorldMainApplication和Controller配合使用:
@SpringBootApplication
public class HelloWorldMainApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldMainApplication.class,args);
}
}
注解介绍
@SpringBootApplication
:标致在springboot的主程序上SpringApplication.run
方法中需要传入有主程序注解的类。
@SpringBootApplication注解包含以下注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration //表明是springboot配置类
@EnableAutoConfiguration //告诉springboot开启自动配置
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
@SpringBootConfiguration
//表明是springboot配置类@EnableAutoConfiguration
//告诉springboot开启自动配置
@AutoConfigurationPackage 自动配置包,这个注解下的@Import(AutoConfigurationPackages.Registrar.class);将主配置类(@SpringBootApplication标注得类)的所在包,及下面所有子包里面的所有组件扫描到Spring容器
@Import(AutoConfigurationImportSelector.class):将所有需要导入的组件以全类名的方式返回,这些组件就会被添加到容器中。
Controller
@Controller
public class HelloController {
//ResponseBody直接返回到浏览器页面
@ResponseBody
@RequestMapping("/hello")
public String hello(String name){
return "Hello "+name;
}
}