模式注解
Stereotype Annotation俗称为模式注解,Spring中常见的模式注解有@Service,@Repository,@Controller等,它们都“派生”自@Component注解。@Component的派生注解都可以注入到IOC容器里。
@Enable注解
@Enable模块驱动在Spring Framework 3.1后开始支持。这里的模块通俗的来说就是一些为了实现某个功能的组件的集合。通过@Enable模块驱动,我们可以开启相应的模块功能。
@Enable模块驱动可以分为“注解驱动”和“接口编程”两种实现方式。
- 注解驱动
Spring中,基于注解驱动的示例可以查看@EnableWebMvc源码:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}
该注解通过@Import导入一个配置类DelegatingWebMvcConfiguration:
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
基于注解驱动的@Enable模块驱动其实就是通过@Import来导入一个配置类,以此实现相应模块的组件注册,当这些组件注册到IOC容器中,这个模块对应的功能也就可以使用了。
- 接口编程
Spring中,基于接口编程方式的有@EnableCaching注解,查看其源码:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({CachingConfigurationSelector.class})
public @interface EnableCaching {
boolean proxyTargetClass() default false;
AdviceMode mode() default AdviceMode.PROXY;
int order() default 2147483647;
}
EnableCaching注解通过@Import导入了CachingConfigurationSelector类,该类间接实现了ImportSelector接口。
通过接口编程实现@Enable模块驱动的本质是:通过@Import来导入接口ImportSelector实现类,该实现类里可以定义需要注册到IOC容器中的组件,以此实现相应模块对应组件的注册。
在SpringBoot2中,@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 {
...
}
其中,有一个注解@EnableAutoConfiguration,看一下源码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
其中@Import(AutoConfigurationImportSelector.class),借助AutoConfigurationImportSelector,@EnableAutoConfiguration可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建并使用的IoC容器。
因此,第一种方式只需要写配置类就可以了。