Spring --@Primary注解

1.问题

当一个接口有2个不同实现时,使用@Autowired注解时会报org.springframework.beans.factory.NoUniqueBeanDefinitionException异常信息

2.方案1-@Qualifier

使用Qualifier注解,选择一个对象的名称,通常比较常用

3.方案2-@Primary

Primary可以理解为默认优先选择,同时不可以同时设置多个,
内部实质是设置BeanDefinition的primary属性

以下是一个例子:

package cn.myframe.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Primary
@Component("metalSinger") // 加注解,让spring识别
 class MetalSinger implements Singer{

	@Override
	public String sing(String lyrics) {
		return "I am singing with DIO voice: "+lyrics;
	}
}


@Component("operaSinger")
 class OperaSinger implements Singer {
	@Override
	public String sing(String lyrics) {
		return "I am singing in Bocelli voice: "+lyrics;
	}
}

 interface Singer {
	String sing(String lyrics);
}

@Component
public class SingerService {
	@Autowired
//	@Qualifier("metalSinger")
	private Singer singer;
	public String sing(){
		return singer.sing("song lyrics");
	}

	public static void main(String[] args) {

		ApplicationContext context = new AnnotationConfigApplicationContext("cn.myframe.test");
		SingerService singerService = context.getBean(SingerService.class);
		System.out.println(singerService.sing());
	}

}

你可能感兴趣的:(Spring)