Spring Boot 中那些常用的Annotation

1. @ComponentScan

@ComponentScan是SpringBoot框架魔法得意实现的一个关键组件。

@ComponentScan 对应 XML 配置形式中的 <context:component-scan> 元素,用于配合一些元信息 Java Annotation,比如 @Component 和 @Repository 等,将标注了这些元信息 Annotation 的 bean 定义类批量采集到 Spring 的 IoC 容器中。

我们可以通过 basePackages 等属性来细粒度地定制 @ComponentScan 自动扫描的范围,如果不指定,则默认 Spring 框架实现会从声明 @ComponentScan 所在类的 package 进行扫描。

2. @PropertySource 与 @PropertySources

@PropertySource 用于从某些地方加载 *.properties 文件内容,并将其中的属性加载到 IoC 容器中,便于填充一些 bean 定义属性的占位符(placeholder),当然,这需要 PropertySourcesPlaceholderConfigurer 的配合。

如果我们使用 Java 8 或者更高版本开发,那么,我们可以并行声明多个 @PropertySource:

1 @Configuration
2 @PropertySource("classpath:1.properties")
3 @PropertySource("classpath:2.properties")
4 @PropertySource("...")
5 public class XConfiguration{
6     ...
7 }

如果我们使用的是低于Java 8 版本的Java开发Spring应用,又想声明多个@PropertySource,则需要借助@PropertySoures 的帮助了,代码如下所示:

1 @PropertySources({ @PropertySource("classpath:1.properties"), @PropertySource("classpath:2.properties"), ...})
2 public class XConfiguration{
3     ...
4 }

3. @Import 与 @ImportResource

在 XML 形式的配置中,我们通过 <import resource="XXX.xml"/> 的形式将多个分开的容器配置合到一个配置中,在 JavaConfig 形式的配置中,我们则使用 @Import 这个 Annotation 完成同样目的:

1 @Configuration
2 @Import(MockConfiguration.class)
3 public class XConfiguration {
4     ...
5 }

@Import 只负责引入 JavaConfig 形式定义的 IoC 容器配置,如果有一些遗留的配置或者遗留系统需要以 XML 形式来配置(比如 dubbo 框架),我们依然可以通过 @ImportResource 将它们一起合并到当前 JavaConfig 配置的容器中。

posted @ 2020-05-25 15:07  AltFahrer  阅读(317)  评论(0)    收藏  举报