Java Spring 5:NullBean类CastException

Java Spring 5:NullBean类CastException,java,spring,Java,Spring,我有一个bean方法,如果条件不满足,它会有条件地返回有效的初始化bean或null值。如下所示: @Bean public MyBean myBean() { if(this.activated) { // decides if the bean is needed return new MyBean(); } else { return null; } } 当我使用3.2.8.0版本的Spring时,这项工作没有任何问题。然而,当我在Spring5中运行这段代

我有一个bean方法,如果条件不满足,它会有条件地返回有效的初始化bean或null值。如下所示:

@Bean
public MyBean myBean() {
  if(this.activated) {  // decides if the bean is needed
    return new MyBean();
  } else {
    return null;
  }
}
当我使用3.2.8.0版本的Spring时,这项工作没有任何问题。然而,当我在Spring5中运行这段代码时,我得到了一个使用这个bean的类强制转换异常,并显示了一条消息

org.springframework.beans.factory.support.NullBean cannot be cast to com.myproject.MyBean
其中
NullBean
似乎是在Spring5中引入的

我被限制在编译时使用Spring3.x,但是如果可能的话,我还希望使代码在Spring5环境中可以执行,并且代码更改很少或没有更改

我曾经考虑过使用概要注释,但是,还有其他更简单、更快的方法可以替代吗


提前感谢。

不要从
@Bean
方法返回
null
,这是一个非常糟糕的主意,并且可能有危险。您应该有条件地添加一个配置类(或bean),但使用Spring3.2这有点困难,但并非不可能。