日期:2014-05-18  浏览次数:20595 次

spring注解问题,spring是怎么知道往这个接口里注入实现类别对象的?
以前用xml做配置的时候,因为spring的bean配置有属性字段,看的很清晰,最近开始学习用注解配置,结果开始搞不明白原理了,示例如下
有一接口
public interface GameInfoService {}

有一实现了它的类

@Service
public class GameInfoServiceImpl implements GameInfoService {}

然后在另外一个类别里,有一个GameInfoService 对象
@Component("gameInfoAction")
public class GameInfoAction extends ActionSupport {

private GameInfoService gameInfoService;

@Resource
public void setGameInfoService(GameInfoService gameInfoService) {
this.gameInfoService = gameInfoService;
}
}

然后在实际运行中,通过测试得知,GameInfoAction 内部的gameInfoService接口实际上被注入了GameInfoServiceImpl对象

我的疑问是,为啥呢,这里的规则是什么,spring为啥会确定这里应该注入GameInfoServiceImpl对象,就因为GameInfoServiceImpl是唯一实现了gameInfoService接口的类别吗?如果实现了gameInfoService接口的类别不止一个,该用什么方法标示注入哪一个?

------解决方案--------------------
我从没用过注解。刚刚网上搜索了注入规则。
@Resource应用在setter上(应用到属性),则注入规则是:
   a.先使用属性名字匹配bean,查找到bean则注入,如果类型不匹配则此时有异常,注入失败
   b.如果属性名字没有匹配到Bean则spring会尝试采用属性参数类型匹配,如果找打bean则注入,如果属性参数类型是接口则有可能会匹配到多个类型,则会抛出匹配到多个
bean的异常.注入失败.

如果intefaces 有多个实现,且自己不指定具体哪个实现,就会报错。