SpringBoot入门
环境准备
- jdk1.8:Spring Boot 推荐jdk1.7及以上;java version “1.8.0_112”
- maven3.x:maven 3.3以上版本;Apache Maven 3.5.4
- SpringBoot 2.0.4 .RELEASE:2.0.4
下面我们通过一个具体的案例来演示springboot的运行效果。
需求: 向浏览器发送一个hello请求,服务器接收请求并处理,在页面上显示 ’Hello World‘ 字符串。
创建maven工程
对maven还不太熟悉的童鞋可以参考利用maven创建Java项目
导入Spring Boot相关依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐web</artifactId>
</dependency>
</dependencies>
编写主程序,启动springboot应用
/**
* @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用
*/
@SpringBootApplication
public class HelloWorldMainApplication {
public static void main(String[] args) {
// 启动Spring应用
SpringApplication.run(HelloWorldMainApplication.class,args);
}
}
编写相关的Controller
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "Hello World!";
}
}
在浏览器中输入localhost:8080/hello 就能看到Hello World!
探究Hello World案例
我们首先来看POM文件
POM文件
POM文件中的 标签是用来管理父项目依赖的。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent>
他的父项目是
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath>../../spring-boot-dependencies</relativePath>
</parent>
这里管理着Spring Boot应用里面的所有依赖版本;
这意味着,以后我们导入的依赖,默认是不需要写版本的(没有在dependencies里面管理的依赖依旧需要声明版本)
主程序类
@SpringBootApplication: 该注解说明这个类是Spring Boot的主配置类,Spring Boot就应该运行这个类的main方法来启动springboot应用。
@SpringBootApplication注解中依旧存在一系列的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
@SpringBootConfiguration是Spring Boot的配置类,标注在某个类上,表示这类是一个Spring Boot的配置类;
@Configuration 标注在配置类上
@EnableAutoConfiguration 开启自动配置功能
以前我们需要配置的东西,Spring Boot帮我们自动配置@EnableAutoConfiguration告诉SpringBoot开启自动配置功能;这样自动配置才能生效;
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
@AutoConfigurationPackage 自动配置包
@Import(AutoConfigurationPackages.Registrar.class):
Spring的底层注解@Import,给容器中导入一个组件;导入的组件由AutoConfigurationPackages.Registrar.class;
将主配置类(@SpringBootApplication标注的类)的所在包及下面所有子包里面的所有组件扫描到Spring容器
EnableAutoConfigurationImportSelector:导入哪些组件的选择器;
将所有需要导入的组件以全类名的方式返回;这些组件就会被添加到容器中;
会给容器中导入非常多的自动配置类(xxxAutoConfiguration);就是给容器中导入这个场景需要的所有组件,并配置好这些组件;
有了自动配置类,免去了我们手动编写配置注入功能组件等的工作;
Spring Boot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值,将这些值作为自动配置类导入到容器中,自动配置类就生效,帮我们进行自动配置工作;以前我们需要自己配置的东西,自动配置类都帮我们完成;