spring annotation @Autowired的问题
刚学spring annotation ,用到@Autowired这个注解.
资料上都说@Autowired默认byType ,但经我测试,感觉是byName..
不知道是我测试错了,还是却有这么回事...请各位解释一下..
以下是关键代码:
Boss.java
package com.wp.model;import org.springframework.beans.factory.annotation.Autowired;public class Boss { @Autowired private Car car; @Autowired private Office office; public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public Office getOffice() { return office; } public void setOffice(Office office) { this.office = office; } @Override public String toString() { return office.getOfficeNo() + " " + car.getBrand() + " " + car.getPrice(); }}
<?xml version="1.0" encoding="UTF-8" ?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id="boss" class="com.wp.model.Boss"/> <bean id="office" class="com.wp.model.Office"> <property name="officeNo" value="001"/> </bean> <bean id="office2" class="com.wp.model.Office"> <property name="officeNo" value="002"/> </bean> <bean id="car" class="com.wp.model.Car" scope="singleton"> <property name="brand" value=" 红旗 CA72"/> <property name="price" value="2000"/> </bean></beans>
package com.wp.client;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.wp.model.Boss;public class Client { public static void main(String[] args) { String[] locations = { "spring.xml" }; ApplicationContext ctx = new ClassPathXmlApplicationContext(locations); Boss boss = (Boss) ctx.getBean("boss"); System.out.println(boss); }}
只要bean id 不相等 一个实现类 可以写多个
[解决办法]
tO:6楼,"只要bean id 不相等 一个实现类 可以写多个 "
你说错了吧。你跑了楼主的程序没? 我刚刚跑了下,按楼主的程序我的确实异常了:
Could not autowire field: private fiona.apple.Office fiona.apple.Boss.office; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [fiona.apple.Office] is defined: expected single matching bean but found 2: [office, office2]
但如果我把xml文件中的任意一个office的定义注释掉,就不会有问题了。所以楼主的理解还是正确的,@Autowired是按类型装配的,如果xml文件中有多个相同类型的定义,会出异常。