Spring @Autowired 注入静态变量

本文介绍了一种在Spring框架中解决工具类静态方法依赖注入问题的方法。通过使用setter注入方式,实现了@Service层对象对工具类静态成员变量的有效注入,避免了方法调用时出现NullPointerException。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       在一些工具类中可能会依赖 service 层的对象,一般情况下工具类都是使用静态方法,对应的成员变量也需要声明为静态的,此时如果直接使用 @Autowired 进行依赖注入,在方法调用的时候会报 NullpointerException.

@Component
public final class DocImageUtils {
    @Autowired
    private static ImageFileDao imageFileDao;
    @Autowired
    private static DocImageFileDao docImageFileDao;
}
        为实现 @Autowired 静态注入,可以使用 setter 方法注入,如下:

@Component
public final class DocImageUtils {

    private static ImageFileDao imageFileDao;
    private static DocImageFileDao docImageFileDao;

    @Autowired(required = true)
    public  void setDocImageFileDao(DocImageFileDao docImageFileDao) {
        DocImageUtils.docImageFileDao = docImageFileDao;
    }
    @Autowired(required = true)
    public  void setImageFileDao(ImageFileDao imageFileDao) {
        DocImageUtils.imageFileDao = imageFileDao;
    }
}
 这样在工具类方法中就可以正常使用工具类中的静态成员变量.




评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值