[JAVAee]spring-Bean对象的执行流程与生命周期

执行流程

spring中Bean对象的执行流程大致分为四步:

  1. 启动Spring容器
  2. 实例化Bean对象
  3. Bean对象注册到Spring容器中
  4. 将Bean对象装配到所需的类中

①启动Spring容器,在main方法中获取spring上下文对象并配备spring.

java 复制代码
import demo.*;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    }
}

②实例化Bean对象,spring根据配置文件中的路径搜寻"demo"包中含有注解的类.

通过这些类实例化出Bean对象,并对他们进行初始化Bean对象的属性,

java 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <content:component-scan base-package="demo"></content:component-scan>
</beans>

③将实例化出的Bean对象注册到Spring容器当中.

java 复制代码
@Component
public class UserBean {
    private String name;

    @Bean(name = {"user","wualala"})
    //Bean方法注解,将方法返回的对象存储到spring中变成Bean对象
    public UserBean userBeanMethod(){
        UserBean userBean = new UserBean();
        userBean.name = "wow";
        return userBean;
    }

④Bean对象的使用,将其分配到所需的类中

java 复制代码
@Controller
public class UserController {

    @Resource(name = "user1")
    //@Autowired
    private UserBean userBean;

    public UserBean getUserBean() {
        return userBean;
    }
}

生命周期

此处的生命周期指的是,Bean对象的创建到销毁的过程.

Bean对象的生命周期主要分成五个主要部分:

1.Bean的实例化

2.设置Bean的属性:

  • 实现了各种 Aware 通知的⽅法,如 BeanNameAware、BeanFactoryAware、
  • ApplicationContextAware 的接⼝⽅法;
  • 执⾏ BeanPostProcessor 初始化前置⽅法;
  • 执⾏ @PostConstruct 初始化⽅法,依赖注⼊操作之后被执⾏;
  • 执⾏⾃⼰指定的 init-method ⽅法(如果有指定的话);
  • 执⾏ BeanPostProcessor 初始化后置⽅法

3.Bean初始化

4.使用Bean

5.销毁Bean

相关推荐
xiaolyuh1237 小时前
Spring 框架 核心架构设计 深度详解
spring·设计模式·spring 设计模式
独断万古他化11 小时前
【Spring 核心: IoC&DI】从原理到注解使用、注入方式全攻略
java·后端·spring·java-ee
likuolei11 小时前
Spring AI框架完整指南
人工智能·python·spring
梵得儿SHI11 小时前
(第四篇)Spring AI 核心技术攻坚:多轮对话与记忆机制,打造有上下文的 AI
java·人工智能·spring·springai生态·上下文丢失问题·三类记忆·智能客服实战案
希忘auto11 小时前
SpringBoot之统一数据返回格式
java·spring
今晚务必早点睡11 小时前
系统通信方式实战详解:HTTP、RPC、MQ、WebSocket 各用在什么场景?(附 SDK 示例)
websocket·http·rpc
不吃香菜学java11 小时前
spring-依赖注入
java·spring boot·后端·spring·ssm
ja哇11 小时前
Spring AOP 详细讲解
java·后端·spring
海南java第二人11 小时前
Spring Bean生命周期深度剖析:从创建到销毁的完整旅程
java·后端·spring
阿里巴巴P8资深技术专家15 小时前
基于 Spring AI 和 Redis 向量库的智能对话系统实践
人工智能·redis·spring