spring1-test19-默认根据@Autowired注解标记的成员变量为id查找bean,进行装配

在这里插入图片描述

添加一个BookServiceExt类来看下,在实验18的基础上来理解:

package com.atgugui.service;

import com.atgugui.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BookServiceExt extends BookService {

    @Autowired
    private BookDao bookDao;

    @Override
    public void save() {
        System.out.println("bookSServiceExt被调用了...");
    }
}
<!--@Autowired原理:
    以实验18为例:
    private BookService bookService;
    1.先按照类型去容器中找到对应的组件;bookService = ioc.getBean(BookService.class);
        1:找到一个,找到就赋值
        2:没找到,就抛异常。
        3:找到多个,还是会装配上。
            1.按照变量名作为id,继续匹配。(就像BookService(id=bookService),而BookServiceExt(id=bookServiceExt))
-->
<context:component-scan base-package="com"></context:component-scan>

ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-config.xml");

@Test
public void test02(){
    BookServlet bookServlet = ioc.getBean(BookServlet.class);
    bookServlet.doGet();
}
//测试结果:装配的还是BookSerclet类,而不是BookServletExt,因为id不同。
发布了52 篇原创文章 · 获赞 1 · 访问量 2246

猜你喜欢

转载自blog.csdn.net/Shen_R/article/details/104954816