java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > @Primary注解的作用

Spring中@Primary注解的作用详解

作者:五更琉璃V

这篇文章主要介绍了Spring中@Primary注解的作用详解,@Primary 注解是Spring框架中的一个注解,用于标识一个Bean作为默认的实现类,当存在多个实现类时,通过使用@Primary注解,可以指定其中一个作为默认的实现类,以便在注入时自动选择该实现类,需要的朋友可以参考下

@Primary注解作用详解

此注解时为了标识哪个Bean是默认的Bean

  @Bean
	  public AMapper aMapper1(AConfig aConfig) {
	    return new AMapperImpl1(aConfig);
	  }
	  @Bean
	  @Primary
	  public AMapper aMapper2(AConfig aConfig) {
	    return new AMapperImpl2(aConfig);
	  }

上述代码,当存在多个相同类型的Bean注入时,加上@Primary注解,来确定默认的实现标识。

案例

public interface Worker {
	    public String work();
	}
	@Component
	public class Singer implements Worker {
	    @Override
	    public String work() {
	        return "歌手的工作是唱歌";
	    }
	}
	@Component
	public class Doctor implements Worker {
	    @Override
	    public String work() {
	        return "医生工作是治病";
	    }
	}
	// 启动,调用接口
	@SpringBootApplication
	@RestController
	public class SimpleWebTestApplication {
	    @Autowired
	    private Worker worker;
	    @RequestMapping("/info")
	    public String getInfo(){
	        return worker.work();
	    }
	    public static void main(String[] args) {
	        SpringApplication.run(SimpleWebTestApplication.class, args);
	    }
	}

上述情况下,一个接口多个实现,并且通过@Autowired注入 Worker, 由于@Autowired是通过ByType的形式,来给指定的字段和方法来注入所需的外部资源, 但由于此类有多个实现,Spring不知道注入哪个实现,所以在启动的时候会抛出异常。

Consider marking one of the beans as @Primary,
updating the consumer to accept multiple beans,
or using @Qualifier to identify the bean that should be consumed。

当给指定的组件添加@primary后,默认会注入@Primary的配置组件。

@Component
@Primary
public class Doctor implements Worker {
    @Override
    public String work() {
        return "医生工作是治病";
    }
}

给Doctor 加上@Primary,则默认注入的就是 Doctor 的实现。 浏览器访问:localhost:8080/info

在这里插入图片描述

到此这篇关于Spring中@Primary注解的作用详解的文章就介绍到这了,更多相关@Primary注解的作用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文