马大头 2019-03-14 12:27 采纳率: 0%
浏览 5292

SpringBoot使用@Bean配置某个类后,如果该类出错返回null,如何让其他@Resource注入该Bean的地方不出错?

使用CXF调用远程服务,因为cxf创建连接方法速度比较慢,所以使用@Bean在CxfConfig类中进行配置:

@Component
@Slf4j
public class CxfConfig {

    @Value("${wsdl-url}")
    private String wsdlUrl;

    @Bean
    public JaxWsDynamicClientFactory jaxWsDynamicClientFactory() {
        return JaxWsDynamicClientFactory.newInstance();
    }

    @Bean(autowire = Autowire.BY_NAME, value = "myClient")
    public Client myClient() {
        try {
            return this.jaxWsDynamicClientFactory().createClient(wsdlUrl);
        } catch (Exception e) {
            log.error("【WebService连接异常】: " + e);
        }
        return null;
    }


}

然后在其他类中使用@Resource进行注入

@Resource(name = "myClient")
private Client client;

现在发现一个问题,当WebService服务正常运行时不会有什么问题,但是当WebService服务端不可用时CxfConfig调用createClient时返回了一个null,然后项目启动时就会出现org.springframework.beans.factory.BeanNotOfRequiredTypeException:
Bean named 'myClient' is expected to be of type
'org.apache.cxf.endpoint.Client' but was actually of type 'org.springframework.beans.factory.support.NullBean' 错误,连项目都启动不起来。

请问有什么解决办法吗?比如允许@Bean注入空值 或者在config中做什么操作?

  • 写回答

1条回答 默认 最新

  • 混沌太初 2019-03-14 12:32
    关注
    if(xxx==null){
        new Client(搞几个参数进去,当异常来处理)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示