6.1、场景模拟6.1.1、创建UserDao接口及实现类

package org.rain.spring.dao;/** * @author liaojy * @date 2023/8/5 - 11:05 */public interface UserDao {    void saveUser();}

package org.rain.spring.dao.impl;import org.rain.spring.dao.UserDao;/** * @author liaojy * @date 2023/8/5 - 11:08 */public class UserDaoImpl implements UserDao {    public void saveUser() {        System.out.println("保存成功");    }}

6.1.2、创建UserService接口及实现类

package org.rain.spring.service;/** * @author liaojy * @date 2023/8/5 - 11:10 */public interface UserService {    void saveUser();}

package org.rain.spring.service.impl;import org.rain.spring.dao.UserDao;import org.rain.spring.service.UserService;/** * @author liaojy * @date 2023/8/5 - 11:23 */public class UserServiceImpl implements UserService {    private UserDao userDao;    public UserDao getUserDao() {        return userDao;    }    public void setUserDao(UserDao userDao) {        this.userDao = userDao;    }    public void saveUser() {        userDao.saveUser();    }}

6.1.3、创建UserController

package org.rain.spring.controller;import org.rain.spring.service.UserService;/** * @author liaojy * @date 2023/8/5 - 11:32 */public class UserController {    private UserService userService;    public UserService getUserService() {        return userService;    }    public void setUserService(UserService userService) {        this.userService = userService;    }    public void saveUser(){        userService.saveUser();    }}

6.1.4、配置bean

                                    

6.1.5、测试

    @Test    public void testAutoWireByXML(){        ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-autowire.xml");        UserController userController = ioc.getBean(UserController.class);        userController.saveUser();    }

6.2、两种自动装配方式6.2.1、方式一:byType(常用)6.2.1.1、配置bean

注意:
若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值null
若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常NoUniqueBeanDefinitionException

                

6.2.1.2、测试

6.2.2、方式二:byName(后备)6.2.2.1、配置bean

当在IOC中,有多个兼容类型的bean能够为属性赋值时;可以使用byName的方式,匹配id和属性名相同的bean为属性赋值