1.bean生命周期
1.生命周期步骤
1.通过构造器创建Bean实例
2.为bean注入属性(set),
3.把Bean传递bean前置处理器postProcessBeforeInitialization()
4.调用Bean中初始化方法(需要配置)
5.把Bean传递bean后置处理器postProcessAfterInitialization()
6.获取到Bean对象
7.当容器关闭调用Bean的销毁方法(需要配置)
2.指定初始化和销毁方法的几种方式
- 通过@Bean指定init-methed和destroy-methed属性
- 让Bean类实现InitializingBean和DisposableBean接口
- 在方法上使用@PostConstruct(在bean创建完成和属性赋值完成时),@PreDestroy(在容器销毁之前)
3. 生命周期源码
多个处理器时,如果上一个返回null,则后面的处理器也不会执行
4.实验代码
```java package com.spring5.Bean;
/**
- @Author rainbow
- @Date 2022/6/17 15:49
- @Version 1.0
**/
public class Cat {
public Cat() {
} public void init(){System.out.println("cat 被创建");
} public void Destroy(){System.out.println("init");
} }System.out.println("Destroy");
```java
package com.spring5.Bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* @Author rainbow
* @Date 2022/6/17 15:51
* @Version 1.0
**/
public class MyPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("cat"))
// System.out.println(beanName);
System.out.println("前置处理器执行");
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("cat"))
System.out.println("后置处理器执行");
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}
package com.spring5.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.spring5.Bean.Cat;
import com.spring5.Bean.MyPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;
@Configuration //表示为配置类
public class TxConfig {
//创建bean并指定初始化和销毁方法
@Bean(initMethod = "init", destroyMethod = "Destroy",name = "cat")
public Cat getCat() {
return new Cat();
}
//将自定义后置处理器交给容器管理
@Bean
public MyPostProcessor getMyPostProcessor(){
return new MyPostProcessor();
}
}
2.bean的作用域
- singleton:单实例模式,容器会自动生成bean
- prototype:多实例模式,每次返回的都是新的实例,只有手动获取bean时,容器才会生成bean
- request:仅对http请求起作用,每次请求都会创建新的bean
- session:同一个session共享一个bean
- global-session:所有session共享一个bean