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

本文详细介绍了Spring框架中Bean对象的执行流程,包括启动容器、实例化Bean、注册到容器、属性设置和生命周期管理,以及组件扫描和依赖注入的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

执行流程

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

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

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

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对象的属性,

<?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容器当中.

@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对象的使用,将其分配到所需的类中

@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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值