Bean作用域和生命周期

一.Bean的作用域

1.定义

Bean默认情况下是单例模式(Singleton),所有人的使用都是同一个对象。Bean在整个SpringMVC中只有一份,它是全局共享的。

2.作用域

后四种限定Spring MVC状态使用

(1)Singleton(单例作用域)

该作⽤域下的Bean在IoC容器中只存在⼀个实例:获取Bean(即通过applicationContext.getBean等⽅法获取)及装配Bean(即通过@Autowired注⼊)都是同⼀个对象。Spring默认选择该作用域

(2)prototype(原型作用域)

每次对该作用域下的Bean请求都会创建新的实例。

(3)request(请求作用域)

每次http请求会创建新的Bean实例,类似于prototype

(4)session(会话作用域)

在⼀个http session中,定义⼀个Bean实例。

(5)application(全局作用域)

在⼀个http servlet Context中,定义⼀个Bean实例

(6)websocket(Http WebSocket 作用域)

在⼀个HTTP WebSocket的⽣命周期中,定义⼀个Bean实例

3.设置作业域

使用@Scope标签

	//1.直接设置值
	@Scope("prototype")
	//2.使用枚举值
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Bean
    public User user(){
        User user=new User();
        user.setId(1);
        user.setName("zhangsan");
        return user;
    }

二.Spring执行流程

(1)启动Spring容器

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

(2)实例化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:context="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">
    <context:component-scan base-package="com.java.demo"></context:component-scan>
</beans>

根据配置完成Bean初始化

(3)Bean注册到Spring中(存)

@Controller
public class StudentController {
}

(4)将Bean装配到需要的类中(取)

采用@Autowired注释

三.Bean生命周期

(1)实例化Bean

为Bean分配内存空间

(2)设置属性

Bean注入和装配

(3)Bean初始化

实现了各种Aware 通知的方法,如 BeanNameAware、BeanFactoryAware,ApplicationContextAware 的接口方法;
执行 BeanPostProcessor 初始化前置方法;
执行@PostConstruct初始化方法,依赖注入操作之后被执行;
执行自己指定的init-method 方法
执行 BeanPostProcessor 初始化后置方法。

(4)使用Bean

(5)销毁Bean

销毁容器的各种方法,如 @PreDestroy、DisposableBean 接口方法、destroy-method。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值