寒假学习(6)

Spring 容器
Spring 容器主要的功能是负责创建、配置、管理Bean的生命周期。它提供了以下功能:
1.IoC(控制反转):Spring 容器通过控制对象的创建和依赖注入来实现“反转控制”,即对象不再自己管理依赖的对象,而是由容器来提供依赖。
2.DI(依赖注入):通过构造器、setter 或字段注入等方式,将对象的依赖自动注入到目标对象中。
3.生命周期管理:Spring 容器负责管理 Bean 的创建、初始化、销毁等生命周期操作。

Spring 容器的实现
BeanFactory:是最基本的容器,它提供了最基本的功能,如加载 Bean 配置文件,管理 Bean 的创建与销毁等。
ApplicationContext:是 BeanFactory 的子接口,提供了更多的功能和扩展

Spring 容器的工作流程
1.加载配置:容器从指定的配置源(XML文件、注解类或Java配置类)中读取配置信息。2.创建 Bean:容器根据配置创建 Java 对象(Bean)。
3.依赖注入:容器将所需的依赖注入到每个 Bean 中。
4.初始化 Bean:容器根据配置调用 Bean 的初始化方法。
5.销毁 Bean:容器在应用关闭时销毁 Bean。

Spring 容器的配置方式
基于 XML 的配置

<!-- spring-config.xml -->
<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.xsd">
  
    <!-- 定义一个 Bean -->
    <bean id="car" class="com.example.Car">
        <property name="engine" ref="engine"/>
    </bean>
    
    <bean id="engine" class="com.example.Engine"/>
  
</beans>

基于注解的配置

@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
    // Spring 容器会自动扫描指定包下的类并创建 Bean
}

@Component
public class Car {
    private Engine engine;

    @Autowired
    public Car(Engine engine) {
        this.engine = engine;
    }
}

@Component
public class Engine {
    public void start() {
        System.out.println("Engine starting...");
    }
}

posted @   muxin1630  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示