同一个接口有两个或两个以上实现类时,如何注入

如果有一个接口,但有多个实现类,应如何注入?

例,有一个TestService接口,代码如下:

public interface TestService {
	
	void run();

}

此时有两个实现类实现了这个接口。

实现类一:

@Service("TestServiceImpl")
public class TestServiceImpl implements TestService {

	@Override
	public void run() {
		System.out.println("one");
		
	}

}

实现类二:

@Service("TestServiceTwoImpl")
public class TestServiceTwoImpl implements TestService {

	@Override
	public void run() {
		System.out.println("two");
	}

}

如果此时按照常规@Autowired注入,系统会报错,注入不进去。

@Controller
@RequestMapping("testController")
public class TestController {
	
	@Autowired
	private TestService testService;
	
	@RequestMapping("test")
	public void test() {
		testService.run();
	}
}

@Autowired是按 byType的方式寻找接口的实现类,当要注入的类型在容器中存在多个时,Spring是不知道要引入哪个实现类的,所以会报错。

如何解决

这种场景下,只能通过 byName 注入的方式。可以使用 @Resource 或 @Qualifier 注解。
@Resource 默认是按照 byName 的方式注入的, 如果通过 byName 的方式匹配不到,再按 byType 的方式去匹配。所以上面的引用可以替换为:

@Controller
@RequestMapping("testController")
public class TestController {
	
	@Resource(name = "TestServiceTwoImpl")
	private TestService testService;
	
	@RequestMapping("test")
	public void test() {
		testService.run();
	}

}

运行正常。

或者将@Qualifier与@Autowired组合使用,可替换为:

@Controller
@RequestMapping("testController")
public class TestController {
	
	@Autowired
	@Qualifier("TestServiceTwoImpl")
	private TestService testService;
	
	@RequestMapping("test")
	public void test() {
		testService.run();
	}

}

运行正常。

总结

1、@Autowired 是通过 byType 的方式去注入的, 使用该注解,要求接口只能有一个实现类。
2、@Resource 可以通过 byName 和 byType的方式注入, 默认先按 byName的方式进行匹配,如果匹配不到,再按 byType的方式进行匹配。
3、@Qualifier 注解配合@Autowired 一起使用。


版权声明:本文为weixin_43887814原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。