【问题标题】:Check, if a scoped bean is null检查作用域 bean 是否为空
【发布时间】:2016-01-22 22:27:38
【问题描述】:

在 Spring 的 Java 配置中,我有一个 bean,注释如下:

@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public Object foo() { ... }

此方法有时会返回 null(如果没有要实例化的内容)。在我的代码中,我想检查这种情况,例如:

@Inject
Object foo

if (foo != null)
   foo.be_wise();

但这不起作用,因为 foo 被代理了,因此永远不会为空!因此,检查 null 我能找到的唯一方法是触发 NullPointerException,如下所示:

try
{
  foo.dont_be_wise();
}
catch (NullPointerException e)
{
  be_wise();
}

我不喜欢这样,因为抛出异常代价高昂!

还有其他方法可以检查代理 bean 是否为空吗?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    spring-test 模块 (Spring 4.2.4) 添加了对解包代理的支持。查看相关提交https://github.com/spring-projects/spring-framework/commit/efe3a35da871a7ef34148dfb65d6a96cac1fccb9

    稍作修改的示例(另见AopUtils):

    if (AopUtils.isAopProxy(myBean) && (myBean instanceof Advised)) {
         MyFoo target ((Advised) myBean).getTargetSource().getTarget();
         if (target != null) {
             // ...
         }
    }
    

    虽然这是一种解决方法,但还有其他(可能更优雅的方法)来解决问题:

    空对象

    引入接口的 NoOp 实现可以将 null-ckecks 从客户端代码中抽象出来。见Null Object Design Pattern。 在这种情况下,您的 @Bean 方法将永远不会返回 null

    条件 Bean 注册

    从 Spring 4.0 开始,bean 可以在 @Conditional 的基础上进行实例化。 根据您的用例,这可能是一个选项。 见Conditionally include @Bean methods

    【讨论】:

      【解决方案2】:

      这可能适用于检索代理实例。在 Spring 4.2.4 中,这适用于 @Autowired-injected bean,我认为这基本上是一样的。

      ((org.springframework.aop.framework.Advised) foo).getTargetSource().getTarget()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-17
        • 2010-12-23
        • 2013-07-18
        • 2013-07-12
        相关资源
        最近更新 更多