本文主要是介绍Spring @Primary Annotation Spring的@Primary注解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原文链接:Spring @Primary Annotation
1. Overview 简述
In this quick tutorial, we'll discuss Spring's @Primary annotation which was introduced with version 3.0 of the framework.
和我在这里来讨论下Spring3.0引入的@Primary注解吧。
Simply put, we use @Primary to give higher preference to a bean when there are multiple beans of the same type.
简单来说,使用@Primary注解可以给某个bean对象更高的引用优先级,这个特性,在程序上下文中存在同一类型多个实现时很有效用。
Let's describe the problem in detail. 接下来来详细看一下如何使用吧。
2. Why Is @Primary Needed? 为什么需要这个@Primary注解呢?
In some cases, we need to register more than one bean of the same type.
在某些场景下,我们需要在程序上下文中注册某一接口的多个实现bean对象。
In this example we have JohnEmployee() and TonyEmployee() beans of the Employee type:
在下面的示例中,创建了Employee类型的两个实现bean对象,如下:
@Configuration
public class Config {@Beanpublic Employee JohnEmployee() {return new Employee("John");}@Beanpublic Employee TonyEmployee() {return new Employee("Tony");}
}
Spring
这篇关于Spring @Primary Annotation Spring的@Primary注解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!