Spring Bean的生命周期
1.使用Bean注解添加生命周期方法
1.1@Bean注解源码
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
@AliasFor("name")
String[] value() default {};
@AliasFor("value")
String[] name() default {};
Autowire autowire() default Autowire.NO;
String initMethod() default "";
String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
}
1.2使用案列
public class Student {
public Student(){
System.out.println("Student Construct");
}
public void init(){
System.out.println("Student init");
}
public void destroy(){
System.out.println("Student destroy");
}
}
@Configuration
public class SpringConfig {
@Bean(initMethod = "init",destroyMethod = "destroy")
public Student student(){
return new Student();
}
}
public class SpringApplicationContext {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(SpringConfig.class);
applicationContext.close();
}
}
2.JSR250注解实现初始化和销毁
@Component
public class DemoBean {
@PostConstruct
public void init() {
}
@PreDestroy
public void destroy() {
}
}
3.BeanPostProcessor
3.1作用
- 他的处理时机也相当于生命更周期的一部分
- 可以对全局的bean进行增强,因为他实质是对初始化方法的增强
- 实际上spring中大多数的接口以及注解具体功能的实现都是用过BeanPostProcessor实现的
public interface BeanPostProcessor {
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
3.2案列
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName + ":Bean的前置处理器");
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName + ":Bean的后置处理器");
return bean;
}
}