Spring IoC与DI详解:从Bean概念到手写实现

一、Spring Bean的概念与本质

1.1 什么是Bean?

在Spring框架中,Bean是一个由Spring IoC容器实例化、组装和管理的对象。Bean及其之间的依赖关系通过容器使用的配置元数据来定义。简单来说,Bean就是Spring容器管理的Java对象。简单来说,在Spring里,Bean就是由Spring容器创建、管理和装配的对象,容器负责它的生命周期(创建、初始化、销毁)和依赖注入,开发者无需手动new,直接用就行。

Bean的核心特征:

  • 由Spring容器创建和管理
  • 遵循依赖注入原则
  • 生命周期由容器控制
  • 可以通过名称或类型检索

1.2 Bean与普通Java对象的区别

特性 普通Java对象 Spring Bean
创建方式 通过new关键字创建 由Spring容器创建
依赖管理 手动处理依赖关系 容器自动处理依赖注入
生命周期 由程序员控制 由容器管理
作用域 通常是单例 支持多种作用域(singleton, prototype等)
配置方式 硬编码在程序中 通过配置元数据定义

1.3 Bean的配置元数据

Spring支持三种配置方式定义Bean:

  1. XML配置文件:传统的配置方式
  2. 注解配置:基于Java注解
  3. Java配置类:基于Java代码

本文将重点介绍XML配置方式实现IoC和DI。

二、基于XML的IoC容器实现

2.1 基础环境搭建

首先创建一个Maven项目,添加Spring核心依赖:


    
    
        org.springframework
        spring-context
        5.3.10
    

2.2 创建Spring XML配置文件

在resources目录下创建applicationContext.xml




    
    
    

2.3 创建并获取Bean

public class MainApp {
    public static void main(String[] args) {
        // 1. 加载Spring配置文件,创建容器
        ApplicationContext context = 
            new ClassPathXmlApplicationContext("applicationContext.xml");
        
        // 2. 获取Bean实例
        SimpleBean bean = (SimpleBean) context.getBean("simpleBean");
        
        // 3. 使用Bean
        bean.doSomething();
    }
}

三、依赖注入(DI)的实现方式

3.1 构造器注入

UserService.java

public class UserService {
    private UserRepository userRepository;
    
    // 构造器
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    public void saveUser(User user) {
        userRepository.save(user);
    }
}

applicationContext.xml




    

3.2 Setter方法注入

OrderService.java

public class OrderService {
    private OrderDao orderDao;
    
    // Setter方法
    public void setOrderDao(OrderDao orderDao) {
        this.orderDao = orderDao;
    }
}

applicationContext.xml




    

3.3 字段注入(不推荐)

虽然可以通过字段注入,但推荐使用构造器注入:


    

四、Bean的作用域与生命周期

4.1 Bean的作用域

在XML中通过scope属性定义:











4.2 Bean的生命周期回调

方式一:实现接口

public class LifecycleBean implements InitializingBean, DisposableBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化逻辑
    }
    
    @Override
    public void destroy() throws Exception {
        // 销毁逻辑
    }
}

方式二:XML配置


五、集合类型的依赖注入

5.1 List注入


    
        
            张三
            李四
            王五
        
    

5.2 Map注入


    
        
            
            
        
    

5.3 Properties注入


    
        
            com.mysql.jdbc.Driver
            jdbc:mysql://localhost:3306/test
            root
            123456
        
    

六、自动装配(autowiring)配置

6.1 XML中的自动装配模式












6.2 自动装配的限制与解决方案

问题1:多个同类型Bean









问题2:必须依赖



    

七、基于XML的AOP配置

7.1 配置AOP命名空间



7.2 定义切面






    
    
    
    
    
        
        
        
        
        
    

八、Spring与第三方库集成

8.1 集成JDBC



    
    
    
    




    




    

8.2 集成Hibernate



    
    
        
            org.hibernate.dialect.MySQL5Dialect
            true
            update
        
    
    




    




九、Spring测试框架集成

9.1 配置测试环境



    org.springframework
    spring-test
    5.3.10
    test


    junit
    junit
    4.13.2
    test

9.2 编写集成测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UserServiceTest {
    
    @Autowired
    private UserService userService;
    
    @Test
    public void testSaveUser() {
        User user = new User("test", "[email protected]");
        userService.saveUser(user);
        // 断言验证
    }
}

十、Spring XML配置代码案例

10.1 模块化配置

将大型配置文件拆分为多个小文件:

applicationContext.xml




10.2 使用p命名空间简化配置



    

10.3 使用SpEL表达式


    
    

结语

通过本文的详细讲解,我们全面了解了Spring IoC容器和依赖注入机制在XML配置方式下的实现。从最基本的Bean定义到复杂的AOP配置,从简单的属性注入到集合类型的处理,XML配置方式提供了强大的灵活性和明确的配置结构。虽然现代Spring开发更倾向于使用注解和Java配置,但理解XML配置对于维护遗留系统和深入理解Spring原理仍然非常重要。

你可能感兴趣的:(spring,java,后端,Bean,配置文件,Ioc,DI)