您的位置:首页 > 汽车 > 新车 > spring常用注解(九)@Lazy

spring常用注解(九)@Lazy

2025/1/9 20:20:23 来源:https://blog.csdn.net/w_t_y_y/article/details/142210527  浏览:    关键词:spring常用注解(九)@Lazy

一、介绍

1、简介

@Lazy注解在Spring框架中用于声明一个bean的懒加载行为。当一个bean被标记为@Lazy时,它不会在容器启动时立即初始化,而是在第一次真正需要使用这个bean的时候才进行实例化。这个注解可以用在类或接口、方法上、字段上等。

2、源码
package org.springframework.context.annotation;import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Lazy {boolean value() default true;
}

二、使用场景

1、解决循环依赖
(1)现象
@Service("userService")
public class UserServiceImpl implements UserService {@Autowiredprivate RoleService roleService;@Overridepublic String testUser() {String msg = "这是user";msg = roleService.testRole(msg);System.out.println(msg);return msg;}@Overridepublic String check(String msg) {msg += ":这是user最后check的";return msg;}
}
@Service("roleService")
public class RoleServiceImpl implements RoleService {@AutowiredMenuService menuService;@Overridepublic String testRole(String msg) {msg += ":这是role";return menuService.testMenu(msg);}
}
@Service("menuService")
public class MenuServiceImpl implements MenuService {@Autowiredprivate UserService userService;@Overridepublic String testMenu(String msg) {msg += ":这是Menu";return userService.check(msg);}
}

启动报错:

The dependencies of some of the beans in the application context form a cycle:┌─────┐
|  menuService (field private org.example.service.UserService org.example.service.impl.MenuServiceImpl.userService)
↑     ↓
|  userService (field private org.example.service.RoleService org.example.service.impl.UserServiceImpl.roleService)
↑     ↓
|  roleService (field org.example.service.MenuService org.example.service.impl.RoleServiceImpl.menuService)
└─────┘Action:Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
(2)解决:

在引用处加上@Lazy注解:如我加在UserServiceImpl 引用的地方

@Lazy@Autowiredprivate RoleService roleService;

可以正常启动。

验证功能也正常:

@SpringBootTest(classes = {Main.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class MyTest {@Autowiredprivate UserService userService;@Testpublic void  testUserString(){String msg = userService.testUser();System.out.println("结果:"+msg);}}

正常输出:

这是user:这是role:这是Menu:这是user最后check的
结果:这是user:这是role:这是Menu:这是user最后check的

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com