美文网首页
Spring注解@Primary使用概述

Spring注解@Primary使用概述

作者: 逆水寻洲 | 来源:发表于2019-08-09 11:17 被阅读0次
作用

在声明bean的时候,通过将其中一个可选的bean设置为首选

描述:在spring 中使用注解,常使用@Autowired, 默认是根据类型Type来自动注入的。但有些特殊情况,对同一个接口,可能会有几种不同的实现类,而默认只会采取其中一种。这种情况下 @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注入属性,由于@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 "医生工作是治病";
    }
}

访问结果如下:


image.png

相关文章

网友评论

      本文标题:Spring注解@Primary使用概述

      本文链接:https://www.haomeiwen.com/subject/pllcjctx.html