日期:2014-05-19  浏览次数:20914 次

spring annotation @Autowired的问题
刚学spring annotation ,用到@Autowired这个注解.
资料上都说@Autowired默认byType ,但经我测试,感觉是byName.. 
不知道是我测试错了,还是却有这么回事...请各位解释一下..
以下是关键代码:

Boss.java
Java code
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 code

<?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>





Client.java
Java code

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);
    }

}




输出: 001 红旗 CA72 2000.0



------解决方案--------------------
帮你顶了···虽然最近也学spring,但感觉一头雾水,啥也不懂耶
------解决方案--------------------
@Autowired 是按 byType 自动注入,如果想 byName ,可以使用 @Qualifier
@Resource 默认按 byName 自动注入,只是它是由 JSR-250 规范定义的注释

@Autowired
@Qualifier("beanName")

使用注入后,就不用再 setter/getter 了

至于 LZ 说的那个问题,你真的了解了 什么是 byType , 什么是 byName 了吗 ?
------解决方案--------------------
把office配置换哈 看看是不是002
呵呵!

------解决方案--------------------
楼主还是不理解spring ,建议多看看文档!
@Autowired(默认按类型查找,若没有查到 不会再去用名称查找)

byType 按照类型装配 可以根据属性类型 在容器中寻找跟该类型匹配的bean如果发现多个会抛出异常 如果没有找到属性值设置为null

byName 按照名称装配 根据属性名称 在容器中寻找该属性名称相同的bean 如果找不到 属性值