跳到主要内容

springboot理解

01 springboot简介

简化spring使用的难度,快速开发脚手架,配置简化、内嵌服务器。

springboot是用于快速开发的spring框架,springcloud是完整的微服务框架,依赖springboot

主要优点:

易上手、开箱即用,内嵌服务器、运行监控、外部化配置。

02 springboot核心注解

@SpringBootApplication,包含以下三个注解

  • @SpringBootConfiguration

    包含@Configuration注解,实现配置功能

  • @EnableAutoConfiguration

    打开自动配置功能,也可以关闭某个自动配置的选项,例如关闭数据源自动配置功能

    @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })

    从配置文件META-INF/spring.factories加载可能用到的自动配置类,去重,并去除exclude和excludeName属性携带的类,过滤,将满足条件(@Conditional)的自动配置类返回。

  • @ComponentScan

    spring组件扫描

03 springboot starter工作原理

springboot启动时,@SpringBootConfiguration注解,会去读取每个starter中的META-INF/spring.factories文件,文件里配置了所有需要被创建到spring容器中的bean,并进行自动配置,把bean注入到SpringContext中。

stater提供一个自动化配置类,一般为xxxAutoConfiguration,这个配置类中,通过条件注解来决定一个配置是否生效。然后提供了一系列的默认配置,允许开发者根据实际情况自定义这些配置。

04 如何在springboot启动的时候运行一些特定的代码

可以实现接口ApplicationRunner或者CommandLineRunner,实现run方法,会在springboot的main方法执行完之前被调用,可以用来做一些初始化之类的工作。

05 springboot读取配置的方式

可以通过@PropertySource @Value @Environment @ConfigurationProperties这些注解来绑定变量

06 javaConfig

javaconfig提供了配置spring容器的纯java方法。减少xml的配置。

常用的java config:

@Configuration 在类上使用,标识这个类是配置类

@ComponentScan 配置类上添加,默认扫描该类所在包下的所有配置类,可以指定包名,相当于xml的<context:component-scan>

@Bean bean声明,相当于xml的<bean id="xxx", class="xxx">

@EnableWebMvc 相当于xml的<mvc:annotation-driven> Spring 注解 @EnableWebMvc 工作原理-CSDN博客

@ImportResource 相当于xml的<import resource="xxx.xml">

07 全局异常处理

@ControllerAdvice + @ExceptionHandler

@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中

@ControllerAdvice
public class MyControllerAdvice {

/**
* 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {}

/**
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值
* @param model
*/
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("author", "Magical Sam");
}

/**
* 全局异常捕捉处理
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 100);
map.put("msg", ex.getMessage());
return map;
}

}

see SpringBoot 面试问答总结(VIP典藏版)-阿里云开发者社区