那些高曝光的Annotation(@ComponentScan、@PropertySource与@PropertySources、@Import与ImportResource)

那些高曝光的Annotation(@ComponentScan、@PropertySource与@PropertySources、@Import与ImportResource),第1张

那些高曝光的Annotation(@ComponentScan、@PropertySource与@PropertySources、@Import与ImportResource) 那些高曝光的Annotation 1、@ComponentScan

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

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

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

2、@PropertySource与@PropertySources

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

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

@Configuration
@PropertySource("classpath:1.properties")
@PropertySource("classpath:2.properties")
@PropertySource("...")
public class XConfiguration{
    ...
}

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

@PropertySources({
    @PropertySource(classpath:1.properties),
    @PropertySource(classpath:1.properties),
    ...
})
public class XConfiguration{
    ...
}
3、@import与importResource

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

@Configuration
@import(MockConfiguration.cass)
public class XConfiguration{
    ...
}

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

@Configuration
@import(MockConfiguration.class)
@importResource("...")
public class XConfiguration{
    ...
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5693633.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存