Spring 中可以
延迟加载的优缺点很明显:
所以需酌情使用。
示例代码:
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