装配Bean:JavaConfig@Component@ComponentScan@Configuration

包扫描+JavaConfig方式加载Beans
@Component
@ComponentScan
@Configuration

接口类

package com.xbz.learn.spring.autowire;

public interface MobilePhone {
    /**
     * 给XXX打电话
     * @param phoneNumber
     */
    public void callPerson(String phoneNumber);
}

实现类

package com.xbz.learn.spring.autowire;

import org.springframework.stereotype.Component;

/**
 * MobilePhone接口的iphone实现类
 * @author xbz
 *
 */
@Component("iphone")
public class Iphone implements MobilePhone{

    public void callPerson(String phoneNumber) {
        System.out.println("iphone 正在向【"+phoneNumber+"】打电话");
    }

}
package com.xbz.learn.spring.autowire;

import org.springframework.stereotype.Component;

@Component("xiaomi")
public class XiaoMiPhone implements MobilePhone {

    public void callPerson(String phoneNumber) {
        System.out.println("小米手机 正在向【"+phoneNumber+"】打电话");
    }

}

JavaConfig类

package com.xbz.learn.spring.autowire.javaConfig;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.xbz.learn.spring.autowire.MobilePhone;

@Configuration
@ComponentScan(basePackageClasses={MobilePhone.class})
public class SpringJavaConfig {


}

测试类

package com.xbz.learn.spring.autowire.javaConfig;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.xbz.learn.spring.autowire.MobilePhone;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={SpringJavaConfig.class})
public class SpringJavaConfigTest {

    @Autowired()
    private MobilePhone iphone;

    @Autowired()
    private MobilePhone xiaomi;

    @Test
    public void testJavaConfig(){
        System.out.println("iphone:"+iphone);
        System.out.println("xiaomi:"+xiaomi);
        iphone.callPerson("iphone");
        xiaomi.callPerson("xiaomi");
        System.out.println("is same?"+(iphone==xiaomi));
    }
}


都说@Autowired默认类型匹配,但是我上面IOC容器明明有两个MobilePhone接口的不同实现类,为什么测试正常呢???当我将其中一个变量名改为小米2时,就会出现报错。

所以我猜测
1.@Autowired是变量名称优先,没有才会是类型匹配。
2.先按照类型匹配,发现有多个时,就会用变量名称匹配,如果不存在,则报错。(似乎这个比较合理)

你可能感兴趣的:(spring)