1.@ComponentScan
@ComponentScan对应XML配置形式中的<context:component-scan>元素,用于配合一些元信息Java Annotation,比如@Component和@Repository等,将标注了这些元信息Annotation的bean定义类批量采集到Spring的IoC容器中。可以通过basePackages等属性来细粒度地定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描。
2.@PropertySource与@PropertySources
@PropertySource用于从某些地方加载*.properties文件内容,并将其中的属性加载到IoC容器中,属性文件会加载到Spring的Environment对象中 ,便于填充一些bean定义属性的占位符(placeholder),当然,这需要PropertySourcesPlaceholderConfigurer的配合。
当java 8 或者更高版本时使用方法
@Configuration
@PropertySource("classpath:1.properties")
@PropertySource("classpath:2.properties")
@PropertySource("...")
public class XConfiguration{
...
}
当低于java 8版本时使用方法
@PropertySources({
@PropertySource("classpath:1.properties"),
@PropertySource("classpath:2.properties"),
...
})
public class XConfiguration{
...
}
3.@Import与@ImportResource
在XML形式的配置中,我们通过<import resource="XXX.xml"/>的形式将多个分开的容器配置合到一个配置中,在JavaConfig形式的配置中,我们则使用@Import这个注解完成同样目的
@Configuration
@Import(MockConfiguration.class)
public class XConfiguration {
...
}
@Import只负责引入JavaConfig形式定义的IoC容器配置,如果有一些遗留的配置或者遗留系统需要以XML形式来配置(比如dubbo框架),我们依然可以通过@ImportResource将它们一起合并到当前JavaConfig配置的容器中:
@Configuration
@Import(MockConfiguration.class)
@ImportResource("...")
public class XConfiguration {
...
}
4、@Conditional注解
如果给定的条件计算结果为true,就会创建这个bean,否则 的话,这个bean会被忽略。
5、@Primary
优选策略能够与@Component组合用在组件 扫描的bean上,也可以与@Bean组合用在Java配置的bean声明中。在自动装配产生歧义时可使用@Primary注解表示首选。在xml中则使用primary=“true”
6、@Qualifier
注解在注入的时候通过名称指定想要注入进去的是哪个 bean