Bean 初始化(Initialization)
@PostConstruct 标注方法
实现InitializingBean 接口的afterPropertiesSet() 方法
自定义初始化方法
• XML 配置:<bean init-method=”init” … />
代码里没讲, 与注解是一个性质的
• Java 注解:@Bean(initMethod=”init”)
• Java API:AbstractBeanDefinition#setInitMethodName(String)
思考:假设以上三种方式均在同一Bean 中定义,那么这些方法的执行顺序是怎样?
spring bean初始化顺序:PostConstruct->afterPropertiesSet->自定义init方法
搞清楚初始化顺序对于捋清楚自己的实现以及不出现依赖倒转等问题是有帮助的.
代码示例
spring-core项目
搜索 37 | 初始化Spring Bean
BeanInitializationDemo.java
DefaultUserFactory.java
BeanInitializationDemo.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.geekbang.thinking.in.spring.bean.definition;
import org.geekbang.thinking.in.spring.bean.factory.DefaultUserFactory;
import org.geekbang.thinking.in.spring.bean.factory.UserFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
/**
* 37 | 初始化Spring Bean:Bean初始化有哪些方式?
*
* Bean 初始化 Demo
* • Bean 初始化(Initialization)
* • 37.1 @PostConstruct 标注方法, 这是一个jdk标准实现
* • 37.2 实现InitializingBean 接口的afterPropertiesSet() 方法
* 见 DefaultUserFactory中
* • 自定义初始化方法
* • XML 配置:<bean init-method=”init” ... />
* • 37.3.2 Java 注解:@Bean(initMethod=”init”)
* • Java API:AbstractBeanDefinition#setInitMethodName(String)
* spring 1.0 开始 setInitMethodName 就已经在 AbstractBeanDefinition 中了
* 从 spring 5.0 开始setInitMethodName被提取到 BeanDefinition中
* 就是 @Bean(initMethod = "initUserFactory", destroyMethod = "doDestroy")
* initMethod的实现
* 这里验证方式是在setInitMethodName方法上打断点, 断点上右键, 设置
* "initUserFactory".equals(initMethodName)
*
* spring bean初始化顺序:PostConstruct->afterPropertiesSet->自定义init方法
*
* 搞清楚初始化顺序对于捋清楚自己的实现以及不出现依赖倒转等问题是有帮助的.
*
* 38 | 延迟初始化Spring Bean:延迟初始化的Bean会影响依赖注入吗?
* • Bean 延迟初始化(Lazy Initialization)
* 38.1.1 XML 配置:<bean lazy-init=”true” ... />
* 38.1.2 Java 注解:@Lazy(true)
*
* 当 @Lazy Bean 的注入和初始化。当注入过程中,@Lazy Bean 是一个代理对象,当程序调用这个 Bean 的方法时才会开始初始化。
* 因此, 延迟初始化的Bean是在Spring 应用上下文已启动后, 调用时才会初始化
* 非延迟初始化 @Lazy(value = false) 的Bean则是在 Spring 应用上下文启动前 就完成了初始化
*
* 39 | 销毁Spring Bean: 销毁Bean的基本操作有哪些?
* • Bean 销毁(Destroy)
* • @PreDestroy 标注方法
* • 实现DisposableBean 接口的destroy() 方法
* • 自定义销毁方法
* • XML 配置:<bean destroy=”destroy” ... />
* • Java 注解:@Bean(destroy=”destroy”)
* • Java API:AbstractBeanDefinition#setDestroyMethodName(String)
*
* spring bean销毁顺序:@PreDestroy->destroy()->自定义销毁方法
*
* 销毁是由 applicationContext.close(); 触发的
* 顺序是:
* org.springframework.context.support.AbstractApplicationContext#close() -> #doClose() -> # destroyBeans() ->
* org.springframework.beans.factory.config.ConfigurableBeanFactory#destroySingletons() 找实现类 ->
* org.springframework.beans.factory.support.DefaultListableBeanFactory#destroySingletons() -> #destroySingletons() ->
* org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#destroySingleton(java.lang.String)
* 直接进行了强转, 然后进行有标注销毁的对象的销毁
* public void destroySingleton(String beanName) {
* // Remove a registered singleton of the given name, if any.
* removeSingleton(beanName);
*
* // Destroy the corresponding DisposableBean instance.
* DisposableBean disposableBean;
* synchronized (this.disposableBeans) {
* disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
* }
* destroyBean(beanName, disposableBean);
* }
* 最后会显式的调用我们自己实现的destroy()方法
*
* @PreDestroy注解的实现方式则需要用到idea的一个功能, 在注解上右键或者 alt+F7, found usages
* 可以发现对应的实现在
* org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor
*
*
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since
*/
@Configuration // Configuration Class, 可写可不写
public class BeanInitializationDemo {
public static void main(String[] args) {
// 创建 BeanFactory 容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
// 注册 Configuration Class(配置类)
applicationContext.register(BeanInitializationDemo.class);
// 启动 Spring 应用上下文
applicationContext.refresh();
// 非延迟初始化在 Spring 应用上下文启动完成后,被初始化
System.out.println("Spring 应用上下文已启动...");
// 依赖查找 UserFactory
UserFactory userFactory = applicationContext.getBean(UserFactory.class);
System.out.println(userFactory);
System.out.println("Spring 应用上下文准备关闭...");
// 关闭 Spring 应用上下文
applicationContext.close();
System.out.println("Spring 应用上下文已关闭...");
}
/**
* 37.1 不指定 initMethod = "initUserFactory", destroyMethod = "doDestroy"
* 则默认找DefaultUserFactory 中 @PostConstruct 标注的初始化方法
*
* 37.3.2 Java 注解:@Bean(initMethod=”init”)
*
* 38.1.2 Java 注解:@Lazy(true)
*
* 39.3 自定义销毁方法 @Bean(destroy=”destroy”)
* @return
*/
@Bean(initMethod = "initUserFactory", destroyMethod = "doDestroy")
@Lazy(value = false)
public UserFactory userFactory() {
return new DefaultUserFactory();
}
}
DefaultUserFactory.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.geekbang.thinking.in.spring.bean.factory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* 36 | 实例化Spring Bean:Bean实例化的姿势有多少种?
* 36.3 默认 {@link UserFactory} 实现
*
* 37 | 初始化Spring Bean:Bean初始化有哪些方式?
*
* 39 | 销毁Spring Bean
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since
*/
public class DefaultUserFactory implements UserFactory, InitializingBean, DisposableBean {
// 37.1. 基于 @PostConstruct 注解
@PostConstruct
public void init() {
System.out.println("@PostConstruct : UserFactory 初始化中...");
}
public void initUserFactory() {
System.out.println("自定义初始化方法 initUserFactory() : UserFactory 初始化中...");
}
/**
* 37.2 实现InitializingBean 接口的afterPropertiesSet() 方法
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean#afterPropertiesSet() : UserFactory 初始化中...");
}
/**
* 39.1 @PreDestroy 标注方法
*/
@PreDestroy
public void preDestroy() {
System.out.println("@PreDestroy : UserFactory 销毁中...");
}
/**
* 39.2 实现DisposableBean 接口的destroy() 方法
* @throws Exception
*/
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean#destroy() : UserFactory 销毁中...");
}
public void doDestroy() {
System.out.println("自定义销毁方法 doDestroy() : UserFactory 销毁中...");
}
/**
* 40 Spring Bean 覆盖的finalize() 方法
* 垃圾回收时 ,finalize()会被java回调
* @throws Throwable
*/
@Override
public void finalize() throws Throwable {
System.out.println("当前 DefaultUserFactory 对象正在被垃圾回收...");
}
}