Spring @Primary注解示例

x33g5p2x  于2022-10-06 转载在 Spring  
字(4.3k)|赞(0)|评价(0)|浏览(363)

在这篇文章中,我们将讨论Spring的@Primary注解,它是在框架的3.0版本中引入的。

简单地说,当有多个相同类型的Bean时,我们使用@Primary来给一个Bean更高的优先权。
让我们来详细描述一下这个问题。

为什么需要@Primary?

在某些情况下,我们需要注册超过一个相同类型的Bean。

在这个例子中,我们有mySQLConnection()oracleConnection()类型的豆子。

@Configuration
public class Config {
 
    @Bean
    public Connection mySQLConnection() {
        return new MySQLConnection();
    }
 
    @Bean
    public Connection oracleConnection() {
        return new OracleConnection();
    }
}

如果我们试图运行该应用程序,Spring会抛出NoUniqueBeanDefinitionException
为了访问具有相同类型的Bean,我们通常使用@Qualifier("beanName")注解。

我们在注入点和@Autowired一起应用。在我们的例子中,我们在配置阶段选择了Bean,所以@Qualifier不能在这里应用。我们可以通过下面的链接了解更多关于@Qualifier注解的信息。
为了解决这个问题,Spring提供了@Primary注解。下面的例子展示了如何在spring应用程序中使用@Primary注解。

@Primary注解可用于任何直接或间接使用@Component注解的类,或使用@Bean注解的工厂方法。在这个例子中,我们将使用@Primary注解与@Component注解。

Spring @Primary注解示例

让我们创建一个例子来演示在Spring应用程序中使用@Primary注解的用法。

使用的工具和技术

  • Spring Framework - 5.1.0.RELEASE
  • JDK - 8或更高版本
  • Maven - 3.2以上
  • IDE - Eclipse Mars/STS

创建一个简单的Maven项目

使用你喜欢的IDE创建一个简单的Maven项目,关于打包结构请参考下面的章节。如果你是maven新手,请阅读本文《如何创建一个简单的Maven项目》。

项目结构

下图显示了项目结构,供您参考。

the pom.xml File

<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.spring</groupId>
    <artifactId>spring-primary-annotation</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-scope-example</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
     <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context</artifactId>
           <version>5.1.0.RELEASE</version>
       </dependency>
    </dependencies>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
           <plugins>
              <plugin>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <version>3.5.1</version>
                  <configuration>
                      <source>1.8</source>
                      <target>1.8</target>
                  </configuration>
              </plugin>
           </plugins>
     </build>
</project>

接下来,考虑以下MessageService接口。

MessageService.java

package net.javaguides.spring.primary;

public interface MessageService {
 public void sendMsg(); 
}

创建三个名为FacebookMessageServiceEmailMessageServiceTwitterMessageService的bean,实现MessageService接口。

FacebookMessageService.java

package net.javaguides.spring.primary;

import org.springframework.stereotype.Component;

@Component
public class FacebookMessageService implements MessageService {
    @Override
    public void sendMsg() {
        System.out.println("FacebookMessageService implementation here");
    }
}

EmailMessageService.java

package net.javaguides.spring.primary;

import org.springframework.stereotype.Component;

@Component
public class EmailMessageService implements MessageService {

    @Override
    public void sendMsg() {
        System.out.println("EmailMessageService Implementation here");
    }
}

TwitterMessageService.java

package net.javaguides.spring.primary;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Primary
@Component
public class TwitterMessageService implements MessageService {
    @Override
    public void sendMsg() {
        System.out.println("TwitterMessageService Implementation here");
    }
}

注意,在上面的TwitterMessageService类中,我们添加了@Primary@Component注解。

基于注解的配置 - AppConfig.java

package net.javaguides.spring.primary;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "net.javaguides.spring.primary")
public class AppConfig {
 
}

运行中的Spring应用程序 - Application.java

让我们创建一个主类并运行一个应用程序。

package net.javaguides.spring.primary;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MessageService messageService = context.getBean(MessageService.class);
        messageService.sendMsg();
        context.close();
    }
}

输出

TwitterMessageService Implementation here

本文的源代码可在我的GitHub存储库中找到https://github.com/RameshMF/spring-core-tutorial

相关文章