大家都会注意到spring-boot的maven引入的包名字普遍的带一个starter
字符串,比如
spring-boot-starter-web
spring-boot-starter-aop
spring-boot-starter-data-jpa
这个其实就是和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.
这个用起来确实很爽,但是如果有时候我虽然引入了这个包,但是在开发过程中暂时不想用到呢。
比如自动引入spring-boot-starter-security
即使你没有配置spring security
,spring-boot也是会默认给你加上一个form-login
的。
这个时候我们需要知道它是在哪儿进行自动配置的。
spring-boot有个显著的main
方法,万年不变,idea启动时也会帮你配好
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
可能很少有人关注@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
同时里面的内容有一个是
/**
* 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 {};
从注释中我们就可以发现这个是我们想要的。
再回到上面的问题,那么如果我们暂时不需要security
的auto-configuration
呢?
那就这么写
@SpringBootApplication(exclude = {
SecurityAutoConfiguration.class,
ManagementWebSecurityAutoConfiguration.class
})
同时别忘了
//@Configuration
//@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
}