SpringBoot的核心註解是哪個?它主要由哪幾個註解組成的?
啓動類上面的註解是@SpringBootApplication,它也是 Spring Boot 的核心註解,主要組合包含了以下 3 個註解:
@SpringBootConfiguration:組合了 @Configuration 註解,實現配置文件的功能
@EnableAutoConfiguration:打開自動配置的功能,也可以關閉某個自動配置的選項,如關閉數據源自動配置功能: @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@ComponentScan:Spring組件掃描。
Spring Boot自動配置原理:
Spring Boot的自動配置註解是 @EnableAutoConfiguration, 從上面的 @Import 的類可以找到下面自動加載自動配置的映射。
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames( getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; }
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) { String factoryClassName = factoryClass.getName(); return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList()); } private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) { MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader); if (result != null) { return result; } else { try { Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories"); LinkedMultiValueMap result = new LinkedMultiValueMap(); while(urls.hasMoreElements()) { URL url = (URL)urls.nextElement(); UrlResource resource = new UrlResource(url); Properties properties = PropertiesLoaderUtils.loadProperties(resource); Iterator var6 = properties.entrySet().iterator(); while(var6.hasNext()) { Entry<?, ?> entry = (Entry)var6.next(); List<String> factoryClassNames = Arrays.asList(StringUtils.commaDelimitedListToStringArray((String)entry.getValue())); result.addAll((String)entry.getKey(), factoryClassNames); } } cache.put(classLoader, result); return result; } catch (IOException var9) { throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var9); } } }
這個方法會加載類路徑及所有jar包下META-INF/spring.factories配置中映射的自動配置的類。
public abstract class SpringFactoriesLoader { /** * The location to look for factories. * <p>Can be present in multiple JAR files. */ public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"; }
查看Spring Boot自帶的自動配置的包:
spring-boot-autoconfigure-xxx.jar 打開其中的META-INF/spring.factories文件會找到自動配置的映射。
發現默認加載了好多的自動配置類,這些自動配置類,會自動給我們加載每個場景所需的所有組件,並配置好這些組件,這樣就省去了很多的配置。
你如何理解 Spring Boot 中的 Starters?
Starters可以理解爲啓動器,它包含了一系列可以集成到應用裏面的依賴包,你可以一站式集成 Spring 及其他技術,而不需要到處找示例代碼和依賴包。
如你想使用 Spring JPA 訪問數據庫,只要加入 spring-boot-starter-data-jpa 啓動器依賴就能使用了。
. . . . . .