我们看几个比较常见的Annotation,便于后面更好的理解spring框架的奥秘做准备
@ComponentScan
对应XML配置形式中的<context: component-scan>元素,用于配合一些元信息Java Annotation,比如@Component和@Repository等,将标注了这些元信息Annotation的bean定义类批量采集到Spring的IoC容器中。
我们可以通过basePackages等属性来细粒度定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在的pakcage进行扫描。
@ComponentScan是SpringBoot框架魔法得以实现的一个关键组件,大家可以重点关注,我们后面还会遇到它。
@PropertySource 与 @PropertySouorces
@PropertySource用于从某些地方加载*.properties文件内容,并将其中的属性加载到IoC容器中,便于填充一些bean定义属性的占位符(placeholder),当然,这需要PropertySourcesPlaceholderConfigurer的配合。
如果我们使用Java8或者更高版本开发,那么,我们可以并行声明多个@PropertySource:
@Configuration
@PropertySource("classpath:1.properties")
@PropertySource("classpath:2.properties")
@PropertySource("...")
public class XConfiguration{
...
}
如果我们使用低于Java8版本的Java开发Spring应用,又想声明多个@PropertySource,则需要借助@PropertySources的帮助了:
@PropertySources({
@PropertySources("classpath:1.properties"),
@PropertySource("classpath:2.properties"),
...
})
public class XConfiguration{
...
}
@Import 与@ImportResource
在XML形式的配置中,我们通过的形式将多个分开的容器配置合到一个配置中,在JavaConfig形式的配置中,我们则使用@Import这个Annotation完成同样的目的:
@Configuration
@Import(MockConfiguration.class)
public class XConfiguration{
...
}
@Import只负责引入JavaConfig形式定义的IoC容器配置,如果有一些遗留的配置或者遗留系统需要以XML形式来配置(比如Dubbo框架),我们依然可以通过@ImportResource将它们一起合并到当前JavaConfig配置的容器中:
@Configuration
@Import(MockConfiguration.class)
@ImportResource("...")
public class XConfiguration{
...
}