Spring boot 2.0教程
一、什么是Spring Boot
Spring Boot 是一个轻量级的开发框架,用来简化基于 Spring 的应用程序的开发工作。相比以前xml的配置方式,spring boot可以使用最少的配置,来完成应用程序开发。
是微服务( Spring Cloud )的基础,用于快速开发各个微服务,即Spring Cloud依赖于Spring Boot。
官网:https://spring.io/projects/spring-boot
特点:
(1)、独立运行:主程序中运行main函数或“java -jar xx.jar”方式。
(2)、不需要外部容器,内嵌的容器(Tomcat),无需war包。
(3)、简化Maven配置:通过一系列的“starter”来简化依赖。
(4)、自动配置Spring:为jar包的类自动配置Bean。
二. 工程搭建
1.运行环境:
JDK1.8
Maven3.3以上
STS(Spring Tool Suite)/ IntelliJ IDEA
2. 搭建方式
2.1 方式一
(1)、创建Maven项目
(2)、pom.xml中添加Spring boot父级依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/>
</parent>
说明:Spring boot依赖此parent的配置,该parent包含了大量默认的配置,大大简化了开发。
2.2 方式二
通过STS/IDEA直接创建Spring Boot项目(此处已STS为例)
New->Other…->Spring Boot->Spring Starter Project ,如图1:
一路“Next”以后
pom.xml文件
增加web支持,pom.xml中增加如下配置:
<!-- spring boot web支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
创建Controller类:Chapter1Controller.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("chapter1/")
public class Chapter1Controller {
@ResponseBody
@RequestMapping("hello")
public String hello() {
return "Hello world! Spring Boot.";
}
}
三、自动配置原理
Spring作为bean容器在启动时,通过在启动类上使用@SpringBootApplication,来开启自动配置工,启动应用时会搜索此注解所在的同级和子集的包,寻找需要加载的bean并完成bean的初始化。此注解的源码:
@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注解:
继承自@Configuration,且功能一致,可以理解为<beans> 。标注当前类是Spring配置类,并且将当前类的,以@Bean注解标记的方法的返回值作为Bean的实例,注册到spring容器中,并且实例名就是方法名。
如:
@SpringBootConfiguration
public class SysConfig {
@Bean
public Map user(){
Map map = new HashMap();
map.put(“name”, “张三”);
map.put(“age”, 99);
return map;
}
}
@EnableAutoConfiguration注解:
让spring boot框架根据类路径下面的jar包依赖,为当前的工程自动注入依赖的类,即自动配置。
例如,引入了“spring-boot-starter-web”模块,则spring boot框架会自动添加tomcat以及spring mvc的依赖。并对tomcat以及spring mvc自动装配。
@ComponentScan注解:
扫描此注解所在的同级和子集的包,寻找需要加载的bean。