SpringBoot常見面試題總結二

一、簡介

前不久已經總結了一篇關於SpringBoot的面試題,文章地址:【https://blog.csdn.net/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.net/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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章