---
title: "使用Spring过程中的疑问"
author: "tom_seed"
date: "2015-04-03T11:15:52Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2015-04-03T11:15:52Z"
id: 2198628
url: "https://tom-seed.iteye.com/blog/2198628"
---

使用Autowired注解进行属性自动注入时，常常会有两个类同时继承一个接口的情况：

```
public interface InterfaceService {
	void doSomething();
}

@Service("interfaceServiceA")
public class InterfaceServiceA implements InterfaceService{
	public void doSomething(){
		System.out.println("xxx");
	}
}

@Service("interfaceServiceB")
public class InterfaceServiceB implements InterfaceService{
	public void doSomething(){
		System.out.println("xxx");
	}
}

@Controller
public class MvcController{
	@Autowired
	InterfaceService interfaceServiceB;
}
```

当存在上面的情况时，一直以为Autowired只通过byType进行Bean的自动装配。需要加@Qualifier("interfaceServiceB")才能注入具体的Bean。

 

其实Autowired自动装配类似于首先进行byType，当发现有多个时再进行byName。

所以，当接口与实现类一对一时，属性名称可以任意定义。一对多时，需要注意属性名必须与Bean在Spring 容器中的ID一致才能有效。