@Lazy注解的使用
@Lazy注解主要有两种用途:
一是可以减少Spring的IOC容器启动时的加载时间。
二是可以解决bean的循环依赖问题。
@Lazy的简介
@Lazy注解用于标识bean是否需要延迟加载。
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Lazy {
/**
* Whether lazy initialization should occur.
*/
boolean value() default true;
}
查看注解源码可知,只有一个参数, 默认为true, 即添加该注解的bean对象就会延迟初始化.
@Lazy的使用
- 准备一个Springboot环境
- 准备两个实体类对象
@Data
@NoArgsConstructor
public class User {
private String name;
private String phone;
private Integer age;
private Person person;
public User(String name, String phone, Integer age) {
System.out.println("我User被初始化了.............");
this.name = name;
this.phone = phone;
this.age = age;
}
}
@Data
@NoArgsConstructor
public class Person {
private String name;
private String phone;
private Integer age;
private User user;
public Person(String name, String phone, Integer age) {
System.out.println("我Person被初始化了.............");
this.name = name;
this.phone = phone;
this.age = age;
}
}
- 添加启动类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public User createUser() {
return new User("韩宣生", "11111", 24);
}
@Bean
@Lazy
public Person createPerson() {
return new Person("韩立", "11111", 24);
}
}
- 测试查看控制台
我User被初始化了.............
- 去掉Person上的 @Lazy注解,重启项目
我User被初始化了.............
我Person被初始化了.............
@Lazy的作用
上面是延时加载Bean对象
下面演示解决循环依赖问题
- 添加两个配置类
@Component
public class PersonConfig {
private UserConfig userConfig;
public PersonConfig( UserConfig userConfig) {
this.userConfig = userConfig;
System.out.println("我是用户配置 PersonConfig");
}
}
@Component
public class UserConfig {
private PersonConfig personConfig;
public UserConfig(PersonConfig personConfig) {
this.personConfig = personConfig;
System.out.println("我是用户配置 UserConfig");
}
}
- 重启项目, 项目报错,代码中存在循环依赖
Description:
The dependencies of some of the beans in the application context form a cycle:
解决办法,给其中一个添加@Lazy注解,如
@Component
public class PersonConfig {
private UserConfig userConfig;
public PersonConfig(@Lazy UserConfig userConfig) {
this.userConfig = userConfig;
System.out.println("我是用户配置 PersonConfig");
}
}
- 重启项目,查看日志
我是用户配置 PersonConfig
我是用户配置 UserConfig
本文来自博客园,作者:NeverLateThanBetter,转载请注明原文链接:https://www.cnblogs.com/do-it-520/p/16774609.html
韶华易逝,不能虚度年华。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器