Spring Bean 延迟加载

2021-01-29

Spring 中可以

  • 在 xml <bean> 中配置参数 lazy-init="true"
  • 可以使用 @Lazy 注解标记 Bean 需要延迟加载

 

延迟加载的优缺点很明显:

  • 提升系统的启动速度,按需要加载 Bean 节约了内存
  • 但不符合 fast-fail 原则,如果系统已经启动完成,在后期的使用过程加载 Bean 出现异常情况比如内存不够,那对系统后期的正常使用影响很大

所以需酌情使用。

 

示例代码:

spring xml 配置

<?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">
        <constructor-arg name="id" value="1"></constructor-arg>
        <property name="name" value="constxiong"/>
    </bean>

    <bean id="user2" class="constxiong.User" lazy-init="true">
        <constructor-arg name="id" value="2"></constructor-arg>
        <property name="name" value="user2"/>
    </bean>
    
    <context:component-scan base-package="constxiong"/>

</beans>

 

User 类

public class User {

	private Integer id;

	private String name;

	public User(Integer id) {
		this.id = id;
		System.out.println("init id:" + id);
	}

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

	public String getName() {
		return name;
	}

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

	@Override
	public String toString() {
		return "User{" +
				"id=" + id +
				", name='" + name + '\'' +
				"}\n" + super.toString();
	}
}

 

测试代码

/**
 * 测试 Bean 延迟加载及区别
 * @author ConstXiong
 */
@Configuration
public class Test {
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring-bean-lazy-init.xml");
//		User user1 = context.getBean("user1", User.class);
//		System.out.println(user1);
//		User user2 = context.getBean("user2", User.class);
//		System.out.println(user2);
//		User user3 = context.getBean("user3", User.class);
//		System.out.println(user3);
	}

	@Bean(name = "user3")
	@Lazy
	static User getUser() {
		User user = new User(3);
		return user;
	}
}

 

打印结果

ConstXiong 备案号:苏ICP备16009629号-3