@RestController注解
@RestController 可以看做是@Controller和@ResponseBody的组合。如果使用@RestController,有请求的时候,spring会扫描到使用注解的类,在请求处理完成之后,spring会直接返回结果字符串给调用者。
@EnableAutoConfiguration注解
@EnableAutoConfiguration注解是spring的自动化配置。。spring尝试着猜测和配置你需要的bean。它是怎么实现的呢?我们下面可以分析一下源码。
@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class
[] exclude() default {};
/**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
String[] excludeName() default {};
}
可以看到代码中通过@Import(EnableAutoConfigurationImportSelector.class)引入了EnableAutoConfigurationImportSelector,而EnableAutoConfigurationImportSelector又实现了selectImports方法。。
@Override public String[] selectImports(AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return NO_IMPORTS; } try { AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader .loadMetadata(this.beanClassLoader); AnnotationAttributes attributes = getAttributes(annotationMetadata); List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes); configurations = removeDuplicates(configurations); configurations = sort(configurations, autoConfigurationMetadata); Set<String> exclusions = getExclusions(annotationMetadata, attributes); checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = filter(configurations, autoConfigurationMetadata); fireAutoConfigurationImportEvents(configurations, exclusions); return configurations.toArray(new String[configurations.size()]); } catch (IOException ex) { throw new IllegalStateException(ex); } }
这个方法会查询
META-INF/spring.factories,当找到spring.factory文件后,SpringFactoriesLoader将查询配置文件的属性,匹配到
org.springframework.boot.autoconfigure.EnableAutoConfiguration之后,会启动这个类中的所有自动配置。。