一、简介

前不久已经总结了一篇关于SpringBoot的面试题,文章地址:【https://blog.csdn/Weixiaohuai/article/details/105621247】,本文将继续总结一些常见的SpringBoot面试题。

二、面试题

【a】SpringBoot核心功能有哪些?

  • 1、独立运行Spring项目
  •     Spring boot 可以以jar包形式独立运行,运行一个Spring Boot项目只需要通过java -jar xx.jar来运行。
  • 2、内嵌servlet容器
  •     Spring Boot可以选择内嵌Tomcat、jetty或者Undertow,这样我们无须以war包形式部署项目。
  • 3、提供starter简化Maven配置
  •     spring提供了一系列的start pom来简化Maven的依赖加载,例如,当你使用了spring-boot-starter-web,会自动加入如图5-1所示的依赖包。
  • 4、自动装配Spring 
  •     SpringBoot会根据在类路径中的jar包,类、为jar包里面的类自动配置Bean,这样会极大地减少我们要使用的配置。当然,SpringBoot只考虑大多数的开发场景,并不是所有的场景,若在实际开发中我们需要配置Bean,而SpringBoot灭有提供支持,则可以自定义自动配置。
  • 5、应用监控
  •     SpringBoot提供基于http ssh telnet对运行时的项目进行监控。
  • 6、无代码生产和xml配置  
  •     SpringBoot不是借助与代码生成来实现的,而是通过条件注解来实现的,这是Spring4.x提供的新特性。

【b】谈谈你熟悉的SpringBoot starter有哪些?

  • spring-boot-starter-web 嵌入tomcat和web开发需要servlet与jsp支持
  • spring-boot-starter-data-jpa 数据库支持
  • spring-boot-starter-data-redis redis数据库支持
  • spring-boot-starter-data-solr solr支持
  • spring-boot-starter-security  安全支持
  • mybatis-spring-boot-starter 第三方的mybatis集成starter

【c】请说明一下几个常用的SpringBoot注解?

  • (1)@RestController和@Controller指定一个类,作为控制器的注解。注意:@RestController = @Controller + @ResponseBody
  • (2)@RequestMapping:映射注解,用于配置请求的映射路径
  • (3)@EnableAutoConfiguration和@SpringBootApplication是类级别的注解,根据maven依赖的jar来自动猜测完成正确的spring的对应配置,只要引入了spring-boot-starter-web的依赖,默认会自动配置Spring MVC和tomcat容器
  • (4)@Configuration:用来标识main方法所在的类,完成元数据bean的初始化
  • (5)@ComponentScan:自动扫描加载所有的Spring组件包括Bean注入,一般用在main方法所在的类上 
  • (6)@ImportResource:当我们必须使用一个xml的配置时,使用@ImportResource和@Configuration来标识这个文件资源的类。
  • (7)@Autowired注解,一般结合@ComponentScan注解,来自动注入一个Service或Dao级别的Bean
  • (8)@Component类级别注解,用来标识一个组件,比如我自定了一个filter,则需要此注解标识之后,Spring Boot才会正确识别

【d】@SpringBootApplication注解包含哪些注解?

  • @SpringBootConfiguration :声明当前类是SpringBoot应用的配置类,项目中只能有一个
  • @EnableAutoConfiguration:开启自动配置,告诉SpringBoot基于所添加的依赖,去“猜测”你想要如何配置Spring
  • @ComponentScan:配置组件扫描的指令。提供了类似与<context:component-scan>标签的作用。通过basePackageClasses或者basePackages属性来指定要扫描的包。如果没有指定这些属性,那么将从声明这个注解的类所在的包开始,扫描包及子包

【e】SpringBoot优缺点

优点:

  •     1、快速构建项目。
  •     2、对主流开发框架的无配置集成。
  •     3、项目可独立运行,无须外部依赖Servlet容器。
  •     4、提供运行时的应用监控。
  •     5、极大的提高了开发、部署效率。
  •     6、与云计算的天然集成。

缺点:

  • 依赖太多,一个spring boot项目就有很多M
  • 缺少服务的注册和发现等解决方案
  • 缺少监控集成方案,安全管理方案

【f】SpringBoot自动配置的原理?

在spring程序main方法中添加@SpringBootApplication或者@EnableAutoConfiguration,会自动去maven中读取每个starter中的spring.factories文件 ,该文件里配置了所有需要被创建spring容器中的bean【加载类路径及所有jar包下META-INF/spring.factories配置中映射的自动配置的类】。

更详细的自动装配说明请参考另外一篇文章:【https://blog.csdn/Weixiaohuai/article/details/106179950】

【g】SpringBoot中的监视器是什么?

Spring boot actuator是Spring启动框架中的重要功能之一。Spring boot监视器可帮助您访问生产环境中正在运行的应用程序的当前状态。有几个指标必须在生产环境中进行检查和监控。即使一些外部应用程序可能正在使用这些服务来向相关人员触发警报消息。监视器模块公开了一组可直接作为HTTP URL访问的REST端点来检查状态。

【h】如何使用SpringBoot实现异常处理?

Spring提供了一种使用ControllerAdvice处理异常的非常有用的方法。 我们通过实现一个ControlerAdvice类,来处理控制器类抛出的所有异常。

【i】Spring Boot 的核心配置文件有哪几个?它们的区别是什么?

  • Spring Boot 的核心配置文件是 application.yml 和 bootstrap.yml 配置文件
  • application 配置文件主要用于 Spring Boot 项目的自动化配置
  • bootstrap 配置文件有以下几个应用场景:
  1.     使用SpringCloud Config配置中心时,这时需要在 bootstrap 配置文件中添加连接到配置中心的配置属性来加载外部配置中心的配置信息;
  2.     一些固定的不能被覆盖的属性;
  3.     一些加密/解密的场景;

【j】Spring Boot 的配置文件有哪几种格式?它们有什么区别?

.properties方式:

spring.application.name=springboot-helloworld

.yml方式:

spring:
  application:
    name: springboot-helloworld

【k】SpringBoot应用有哪几种启动方式?

  • 打包用命令或者放到容器中运行: java -jar xxx.jar --server.port=8081
  • 用 Maven/ Gradle 插件运行(spring-boot-plugin):mvn spring-boot:run -Drun.arguments="--server.port=8888"
  • 直接执行 main 方法运行: 通过开发工具直接运行

【l】如何在 SpringBoot应用启动的时候运行一些特定的代码?

第一种方式:ApplicationRunner方式

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments var1) throws Exception{
        //.....
    }
}

第二种方式:CommandLineRunner方式

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner{
    @Override
    public void run(String... var1) throws Exception{
       //.....
    }
}

两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法。他们都是在SpringApplication 执行之后开始执行的,两个接口中有一个run方法,我们只需要实现这个方法即可

【m】SpringBoot 支持哪些日志框架?默认是哪个?

SpringBoot支持Logging,Log4j2,Lockback作为日志框架,如果你使用starters启动器,SpringBoot将使用Logback作为默认日志框架。无论使用哪种日志框架,SpringBoot都支持配置将日志输出到控制台或者文件中。

【n】SpringBoot 如何定义多套不同环境配置?

提供多套配置文件:applcation.properties

  •     application-dev.properties
  •     application-test.properties
  •     application-prod.properties

结合spring.profile.active=dev指定加载哪个环境的配置

【o】SpringBoot怎么扩展SpringMVC的功能?

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //浏览器发送 /test 请求来到 success
        registry.addViewController("/test").setViewName("success");
    }
}

【p】SpringBoot中使用拦截器怎么校验登录?

创建拦截器:

/**
 * 登陆检查,
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if(user == null){
            //未登陆,返回登陆页面
            request.setAttribute("msg","没有权限请先登陆");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else{
            //已登陆,放行请求
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

注册拦截器:

//所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean //将组件注册在容器
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");
            }

            //注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //super.addInterceptors(registry);
                //静态资源;  *.css , *.js
                //SpringBoot已经做好了静态资源映射
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                        .excludePathPatterns("/index.html","/","/user/login");
            }
        };
        return adapter;
    }

【q】SpringBoot中如何注册Servlet三大组件

通过自定义一个配置类xxxConfiguration,然后配合@Configuration + @Bean注解实现。

【Servlet】:ServletRegistrationBean

@Bean
public ServletRegistrationBean myServlet(){
    ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
    return registrationBean;
}

【Filter】:FilterRegistrationBean

@Bean
public FilterRegistrationBean myFilter(){
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new MyFilter());
    registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
    return registrationBean;
}

【Listener】:ServletListenerRegistrationBean

@Bean
public ServletListenerRegistrationBean myListener(){
    ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
    return registrationBean;
}

 

更多推荐

SpringBoot常见面试题总结二