深入學習Springboot的註解@SpringBootApplication

你好我是辰兮,很高興你能來閱讀,本篇文章是關於Springboot註解的學習,另外補充了一點Springboot的啓動方式小結,總結下來,分享獲取新知,大家一起進步。



一、初識註解

最近在嗶哩嗶哩上面看Java面試會經常看到:說一說你對@SpringBootApplication這個註解的理解?
在這裏插入圖片描述

接下來帶大家一起學習瞭解一下這個註解


@SpringBootApplication是一個組合註解,用於快捷配置啓動類。

@SpringBootApplication包含的三個註解及其含義:

  • @Configuration: 用於定義一個配置類
  • @EnableAutoConfiguration :Spring Boot會自動根據你jar包的依賴來自動配置項目。
  • @ComponentScan: 告訴Spring 哪個packages 的用註解標識的類 會被spring自動掃描並且裝入bean容器。

自動配置、組件掃描,並能夠在他們的“應用程序類”上定義額外的配置,可以使用一個@SpringBootApplication註解來啓用這三個特性。


二、源碼學習

點擊打開@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 {
    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    Class<?>[] exclude() default {};

    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};

    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;
}

1、@SpringBootConfiguration繼承自@Configuration,二者功能也一致,標註當前類是配置類,並會將當前類內聲明的一個或多個以@Bean註解標記的方法的實例納入到spring容器中,並且實例名就是方法名。

2、@EnableAutoConfiguration:是spring boot的核心功能,自動配置。這個註釋告訴SpringBoot“猜”你將如何想配置Spring,基於你已經添加jar依賴項。如果spring-boot-starter-web已經添加Tomcat和Spring MVC,這個註釋自動將假設您正在開發一個web應用程序並添加相應的spring設置.

通常推薦將 @EnableAutoConfiguration 配置在 root 包下,這樣所有的子包、類都可以被查找到。

3、@ComponentScan : 通俗的講,@ComponentScan 註解會自動掃描指定包下的全部標有 @Component註解 的類,並註冊成bean,當然包括 @Component 下的子註解@Service、@Repository、@Controller。@ComponentScan 註解沒有類似 、的屬性


SpringBootApplication繼承了以上三個註解,可以簡化開發,是開發着注重業務。

如在之前掃描註解時,有spring ,springmvc 兩個掃描,導致有兩個bean容器,容易出現錯誤,現在他們都交給了springboot,容器就只有一個,衝突就不會出現了。


三、Springboot的啓動方式

偶爾面試官也會考到爲有幾種啓動Springboot項目的方式 其實有一些 最主要是三種

spring-boot的啓動方式主要有三種:

1. 運行帶有main方法類

2. 通過命令行 java -jar 的方式

3. 通過spring-boot-plugin的方式


1. 最簡單的方法是運行帶有main方法類

在這裏插入圖片描述
然後我們訪問一下測試
在這裏插入圖片描述


2.通過java -jar的方式

使用mvn install先編譯,在使用java -jar xxxxxxxxxx.jar啓動

在項目當前目錄進行編譯,然後 進入target目錄下,使用java命令啓動


3.使用mvn spring-boot:run命令啓動

首先我們的項目中有如下的插件

在這裏插入圖片描述
進入項目當前目錄,然後使用命令
在這裏插入圖片描述
然後項目就啓動了。


4.打包war包,丟到tomcat啓動

5.使用docker容器等等…

未完待續


Java面試Offer直通車


The best investment is to invest in yourself

在這裏插入圖片描述

2020.06.14 記錄辰兮的第82篇博客

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