一、介绍
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的