@Lazy注解使用注意事项

说明:在使用@Autowired注解,自动装配某Bean时,为了避免循环依赖(即自己注入自己,或两个Bean之间互相注入),可使用@Lazy注解,使其不在项目启动的时候就注入Bean,而是在首次使用的时候再注入,即懒加载,可以解决循环依赖的问题。

本文介绍使用@Lazy可能会出现的空指针异常(NPE)。

场景

如下,在 AsyncServiceImpl 内调用本类的方法,自己注入了自己

java 复制代码
import com.hezy.mapper.UserMapper;
import com.hezy.pojo.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Service
public class AsyncServiceImpl {

    @Autowired
    @Lazy
    private AsyncServiceImpl asyncService;

    @Autowired
    private UserMapper userMapper;

    public void insertDTO1(UserDTO userDTO) {
        asyncService.insert(userDTO);
    }

    private void insert(UserDTO userDTO) {
        userMapper.insertUser(userDTO);
    }
}

这种情况,如果不加 @Lazy 注解,启动项目,会报循环依赖错误

问题

启动项目,发现在这里发生了空指针异常

解决

排查下来是因为成员方法insert()为private修饰,换成public就行了,如下:

分析

推测可能与动态代理的方式有关,CGLIB动态代理要求被代理的类或方法不能被final修饰。

对于上述场景,除了修改成员方法的修饰符,把private改为public,还可以考虑不走代理,而直接调用成员方法,如下,都不需要注入自己。

java 复制代码
    @Autowired
    private UserMapper userMapper;

    public void insertDTO1(UserDTO userDTO) {
        insert(userDTO);
    }

    public void insert(UserDTO userDTO) {
        userMapper.insertUser(userDTO);
    }

大家可能有两个问题:


问:为什么要自己注入自己?直接调用成员方法不就行了?

答:因为要考虑到事务,如果用声明式注解,直接调用成员方法,事务会失效。上述代码没有事务问题,故可以直接调用成员方法。


问:为什么方法要用private修饰?直接用public多省事。

答:因为规范,成员方法如果只在本类中使用,须用private修饰。


相关推荐
蒸蒸yyyyzwd23 分钟前
cpp对象模型学习笔记1.1-2.8
java·笔记·学习
qq_297574671 小时前
【实战教程】SpringBoot 集成阿里云短信服务实现验证码发送
spring boot·后端·阿里云
程序员徐师兄1 小时前
Windows JDK11 下载安装教程,适合新手
java·windows·jdk11 下载安装·jdk11 下载教程
RANCE_atttackkk1 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
五岳2 小时前
DTS按业务场景批量迁移阿里云MySQL表实战(下):迁移管理平台设计与实现
java·应用·dts
韩立学长2 小时前
【开题答辩实录分享】以《智能大学宿舍管理系统的设计与实现》为例进行选题答辩实录分享
数据库·spring boot·后端
zhougl9962 小时前
Java 所有关键字及规范分类
java·开发语言
Python 老手3 小时前
Python while 循环 极简核心讲解
java·python·算法
java1234_小锋3 小时前
Java高频面试题:MyISAM索引与InnoDB索引的区别?
java·开发语言
Mr_Xuhhh3 小时前
MySQL函数详解:日期、字符串、数学及其他常用函数
java·数据库·sql