容器启动时,不创建对象,当且第一次获取的时候,才会调用方法创建放在IOC容器中。
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class Person {
private String name;
private int age;
public Person(String name, int age) {
System.out.println("person初始化");
this.name = name;
this.age = age;
}
}
import com.it.vo.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Configuration
public class PersonConfig {
@Lazy
@Bean
public Person person() {
return new Person("刘正", 31);
}
}
import com.it.config.PersonConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class PersonTest {
public static void main(String [] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
System.out.println("IOC容器启动完成");
applicationContext.getBean("person");
}
}
//结果:
IOC容器启动完成
person初始化
本文通过示例展示了在Spring框架中使用@Lazy注解实现懒加载的机制。具体介绍了如何在容器启动时不立即创建对象,而是在首次请求时才实例化,从而优化资源使用。
390

被折叠的 条评论
为什么被折叠?



