在spring boot中有两种注解大家可能分不太清楚,一个是@Enable*,另一个是@EnableConfigurationProperties。其实这两个的原理都是用了@Import注解。@Import导入了配置类。配置类里面的bean都会交给spring容器处理。@Enable*可以通俗得理解为开关,开启了某项功能。
1.这是一个关于Swagger接口文档的配置类添加的注解。
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
@EnableSwagger2
@ConditionalOnProperty(name = "pinda.swagger.enabled", havingValue = "true",matchIfMissing = true)
public class SwaggerAutoConfiguration implements BeanFactoryAware {
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
2.按住ctrl点击@EnableSwagger2,进去之后我们会发现使用了@Import注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({Swagger2DocumentationConfiguration.class})
public @interface EnableSwagger2 {
}
3.按住ctrl点击Swagger2DocumentationConfiguration.class,实际是在加载bean
@Configuration
@Import({SpringfoxWebMvcConfiguration.class, SwaggerCommonConfiguration.class})
@ComponentScan(
basePackages = {"springfox.documentation.swagger2.mappers"}
)
@ConditionalOnWebApplication
public class Swagger2DocumentationConfiguration {
public Swagger2DocumentationConfiguration() {
}
@Bean
public JacksonModuleRegistrar swagger2Module() {
return new Swagger2JacksonModule();
}
@Bean
public HandlerMapping swagger2ControllerMapping(Environment environment, DocumentationCache documentationCache, ServiceModelToSwagger2Mapper mapper, JsonSerializer jsonSerializer) {
return new PropertySourcedRequestMappingHandlerMapping(environment, new Swagger2Controller(environment, documentationCache, mapper, jsonSerializer));
}
}
@EnableConfigurationProperties的查看方式跟上面的一样。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({EnableConfigurationPropertiesRegistrar.class})
public @interface EnableConfigurationProperties {
String VALIDATOR_BEAN_NAME = "configurationPropertiesValidator";
Class<?>[] value() default {};
}