Spring的很多子项目都涉及到配置。在这些项目中,存在一个较为通用的配置模式,了解该模式有助于我们更好地理解框架。本文将对这一模式进行介绍。
我们会以Spring Web MVC框架介绍,之后再结合其他相似的项目进行总结。
1 @Enbale
@Enable*
注解通常指启用某个框架的意思,比如@EnbaleWebMvc
指启用Spring Web MVC框架。该注解一般会配合@Configuration
注解一起使用,放在配置类上,由ApplicationContext
启动时加载。
@Configuration
@EnableWebMvc
public class AppConfig {}
2 @Import
@Import
通常用于引入一个新类,这个类会是一个@Configuration
对象。这样我们可以在应用的@Configuration
配置类上,通过@Import
的方式,引入第三方配置。
@Enbale*
注解往往会在自身的定义上增加@Import
注解,并通过@Import
注解引入一个代理配置类,这样的设计可支持框架提供一套默认的配置。
如下是@EnbaleWebMvc
的源代码,其通过@Import(DelegatingWebMvcConfiguration.class)
引入了Spring Web MVC的核心配置类。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
3 模式总结
下面以Spring Web MVC、Spring WebSocket和Spring STOMP为例,总结下该配置模式。
3.1 Spring Web MVC
-
@EnableWebMvc
注解启用功能; -
@EnableWebMvc
注解上通过@Import(DelegatingWebMvcConfiguration.class)
完成配置功能的加载; -
DelegatingWebMvcConfiguration
内部包含WebMvcConfigurerComposite
,并继承自WebMvcConfigurationSupport
-
WebMvcConfigurationSupport
提供了Spring Web MVC的默认配置 -
WebMvcConfigurerComposite
注入了IoC中所有WebMvcConfigurer
的具体实现类,其自身也是WebMvcConfigurer
的实现类。WebMvcConfigurerComposite
调用注入的所有WebMvcConfigurer
的实现,完成框架的个性化配置
3.2 Spring WebSocket
-
@EnableWebSocket
注解启用功能; -
@EnableWebSocket
注解上通过@Import(DelegatingWebSocketConfiguration.class)
完成配置功能的加载; -
DelegatingWebSocketConfiguration
注入了IoC中所有WebSocketConfigurer
的具体实现类,并继承自WebSocketConfigurationSupport
-
WebSocketConfigurationSupport
提供了Spring WebSocket的默认配置 -
DelegatingWebSocketConfiguration
中注入的WebSocketConfigurer
完成应用的个性化配置
3.3 Spring STOMP
-
@EnableWebSocketMessageBroker
注解启用功能; -
@EnableWebSocket
注解上通过@Import(DelegatingWebSocketMessageBrokerConfiguration.class)
完成配置功能的加载; -
DelegatingWebSocketMessageBrokerConfiguration
注入了IoC中所有WebSocketMessageBrokerConfigurer
的具体实现类,并继承自WebSocketMessageBrokerConfigurationSupport
-
WebSocketMessageBrokerConfigurationSupport
提供了Spring STOMP的默认配置 -
DelegatingWebSocketMessageBrokerConfiguration
中注入的WebSocketMessageBrokerConfigurer
完成应用的个性化配置
5 总结
有时候横向比较不同事物间存在的异同点也是一件非常有意思的事情,甚至有可能在看似毫不相关的东西上经过仔细分析都能发现相似点。