开发者

Spring中@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 Strinwww.devze.comg 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);
	http://www.devze.com    }
	}

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

Consider marking one of the beans as @Primary,

updating the consumer to accept multiple beans,

or usingcufMUkMQ @Qualifier to identify the b编程客栈ean 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注解的作用详解

到此这篇关于Spring中@Primary注解的作用详解的文章就介绍到这了,更多相关@Primary注解的作用内容请搜索编程客栈(pythonwww.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜