Spring - 在未找到bean时注入null而不是抛出异常 [英] Spring - Inject null instead of throwing an exception when bean is not found

查看:103
本文介绍了Spring - 在未找到bean时注入null而不是抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在班上注射了

@Inject IMyInterface controller;

但是没有实现IMyInterface的类。如何使spring注入null而不是抛出 NoSuchBeanDefinitionException 因为我不一定需要它存在?

But there are no classes implementing IMyInterface. How can I make spring inject null instead of throwing NoSuchBeanDefinitionException because I don't necessarily need it to be present?

推荐答案

使用 @Inject (假设它是 javax.inject.Inject ),我认为没有直接的方法来制作绑定可选。但是如果你使用 @Autowired ,你可以将它的必需属性设置为 false

With @Inject (Assuming it is javax.inject.Inject), I think there is no direct way to make the binding optional. But if you use @Autowired, you can set it's required attribute to false:

@Autowired(required = false)
IMyInterface controller;

这篇关于Spring - 在未找到bean时注入null而不是抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆