Bean 初始化的方式与顺序

Bean 在实例化完成后,可以配置初始化,方式如下:

  • @PostConstruct 注解作用于方法
  • 实现 InitializingBean 接口,复写 afterPropertiesSet 方法
  • 自定义 initMethod:xml <bean init-method="init">属性、@Bean(initMethod = "init")、BeanDefinitionBuilder#setInitMethodName

 

示例代码:

spring 配置文件

<?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
                           http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="user1" class="constxiong.User" init-method="init">
        <property name="source" value="xml"/>
    </bean>

    <!-- 开启注解能力 -->
    <context:component-scan base-package="constxiong"/>

</beans>

 

User 类

package constxiong;

import org.springframework.beans.factory.InitializingBean;

import javax.annotation.PostConstruct;

public class User implements InitializingBean {

	private String source;

	private Integer id;
	
	private String name;
	
	public User() {
	}

	@PostConstruct
	public void postConstruct() {
		this.id = 1;
		this.name = "cx1";
		System.out.println(this);
		System.out.println(source + ": User#postConstruct executed
");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.id = 2;
		this.name = "cx2";
		System.out.println(this);
		System.out.println(source + ": User#afterPropertiesSet executed
");
	}

	public void init() {
		this.id = 3;
		this.name = "cx3";
		System.out.println(this);
		System.out.println(source + ": User#init executed
");
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

	@Override
	public String toString() {
		return "User{" +
				"source='" + source + ''' +
				", id=" + id +
				", name='" + name + ''' +
				'}';
	}
}

 

测试代码

package constxiong;


import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试 Bean 的初始化
 * @author ConstXiong
 */
@Configuration
public class Test {
	
	public static void main(String[] args) {
		// xml init
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring-bean-initialization.xml");
		User user1 = context.getBean("user1", User.class);
		System.out.println(user1);

		// @Bean
		User user2 = context.getBean("user2", User.class);
		System.out.println(user2);

		//BeanDefinition
		((DefaultListableBeanFactory)context.getBeanFactory()).registerBeanDefinition("user3",
				BeanDefinitionBuilder.rootBeanDefinition(User.class).setInitMethodName("init").addPropertyValue("source", "BeanDefinition").getBeanDefinition());
		User user3 = context.getBean("user3", User.class);
		System.out.println(user3);
	}

	@Bean(initMethod = "init", name = "user2")
	public User getUser() {
		User user = new User();
		user.setSource("@Bean");
		return user;
	}

}

 

打印结果

User{source='xml', id=1, name='cx1'}
xml: User#postConstruct executed

User{source='xml', id=2, name='cx2'}
xml: User#afterPropertiesSet executed

User{source='xml', id=3, name='cx3'}
xml: User#init executed

User{source='@Bean', id=1, name='cx1'}
@Bean: User#postConstruct executed

User{source='@Bean', id=2, name='cx2'}
@Bean: User#afterPropertiesSet executed

User{source='@Bean', id=3, name='cx3'}
@Bean: User#init executed

User{source='xml', id=3, name='cx3'}
User{source='@Bean', id=3, name='cx3'}
User{source='BeanDefinition', id=1, name='cx1'}
BeanDefinition: User#postConstruct executed

User{source='BeanDefinition', id=2, name='cx2'}
BeanDefinition: User#afterPropertiesSet executed

User{source='BeanDefinition', id=3, name='cx3'}
BeanDefinition: User#init executed

User{source='BeanDefinition', id=3, name='cx3'}

 

打印顺序:@PostConstruct -> InitializingBean #afterPropertiesSet -> initMethd

 

完整代码:008-spring-bean-intitialization

 


【Java学习资源】整理推荐

 

 


【Java面试题与答案】整理推荐

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值