spring-boot自動(dòng)配置

大家都會(huì)注意到spring-boot的maven引入的包名字普遍的帶一個(gè)starter字符串,比如

spring-boot-starter-web
spring-boot-starter-aop
spring-boot-starter-data-jpa

這個(gè)其實(shí)就是和autoConfiguration互相配合使用的,官方文檔中是這么寫的

Auto-configuration is designed to work well with “Starters”, but the two concepts are not directly tied. You are free to pick-and-choose jar dependencies outside of the starters and Spring Boot will still do its best to auto-configure your application.

這個(gè)用起來確實(shí)很爽,但是如果有時(shí)候我雖然引入了這個(gè)包,但是在開發(fā)過程中暫時(shí)不想用到呢。
比如自動(dòng)引入spring-boot-starter-security即使你沒有配置spring security,spring-boot也是會(huì)默認(rèn)給你加上一個(gè)form-login的。

這個(gè)時(shí)候我們需要知道它是在哪兒進(jìn)行自動(dòng)配置的。

spring-boot有個(gè)顯著的main方法,萬年不變,idea啟動(dòng)時(shí)也會(huì)幫你配好

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

可能很少有人關(guān)注@SpringBootApplication注解,于是我們進(jìn)去看里面有什么

@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

同時(shí)里面的內(nèi)容有一個(gè)是

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * @return the classes to exclude
     */
    @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "exclude")
    Class<?>[] exclude() default {};

從注釋中我們就可以發(fā)現(xiàn)這個(gè)是我們想要的。

再回到上面的問題,那么如果我們暫時(shí)不需要securityauto-configuration呢?
那就這么寫

@SpringBootApplication(exclude = {
        SecurityAutoConfiguration.class,
        ManagementWebSecurityAutoConfiguration.class
})

同時(shí)別忘了

//@Configuration
//@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容