@Resource注解相当于By Name装配方式。
TextEditor:
package com.sap;
import javax.annotation.Resource;
public class TextEditor {
private SpellChecker spellChecker;
@Resource(name= "spellChecker223")
public void setSpellChecker( SpellChecker spellChecker ){
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker(){
return spellChecker;
}
public void spellCheck(){
spellChecker.checkSpelling();
}
}
意思是,需要在Beans.xml里寻找一个id 为spellChecker223的bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<!-- Definition for textEditor bean without constructor-arg -->
<bean id="textEditor" class="com.sap.TextEditor">
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker223" class="com.sap.SpellChecker">
</bean>
</beans>
这里的id必须和TextEditor.java里@Resource name属性指定的一致。
要获取更多Jerry的原创文章,请关注公众号"汪子熙":