背景:同样的bean类型有2个。
尝试用autowired+componet或者resource+component来解决。
1、component指定名称示例,id为maizims:
package hello; import org.springframework.stereotype.Component; @Component("maizims") public class MessageServiceImpl implements MessageService { public String getMessage(String str) { return "麦子金服欢迎"+str; } }
可以观察到,直接在component后面的括号里面加上一个字符串即可。字符串的名字就是beanId。
2、autowired。
可以放在成员变量上面,也可以放在构造方法上。
如果有多个bean,需要结合@qualifier使用。
使用方法也简单,直接在qualifier后面的括号里面加个字符串,代表引用的bean的Id
package germmy.groovy import hello.MessageService import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Qualifier; class Simple implements ScriptService { @Autowired @Qualifier("maizims") private MessageService messageService public void run() { String name = messageService.getMessage("16楼MM"); System.out.println(name); } }
3、利用resource。
举例:
package germmy.groovy import hello.MessageService import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Qualifier; class Simple implements ScriptService { @Resource(name="maizims") private MessageService messageService public void run() { String name = messageService.getMessage("16楼MM"); System.out.println(name); } }
总结,既然是用到id来识别的,比如maizims。这个就相当于xml文件中的beanId。
resource用法举例:http://stackoverflow.com/questions/4462466/autowiring-two-different-beans-of-same-class
autowired和qualifier举例:http://stackoverflow.com/questions/15516769/spring-autowire-two-beans-of-the-same-class-which-are-not-defined-in-applicatio
配置文件外挂的用法:http://stackoverflow.com/questions/23555149/spring-3-mvc-using-component-value-to-read-properties-from-a-file-is-not-wor
component扫描多个包的写法,很简单,再加一个就行:https://segmentfault.com/q/1010000000686297
http://www.mkyong.com/spring/spring-autowiring-qualifier-example/ qualifier举例。