首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
EN

Stack Overflow用户
提问于 2020-08-04 12:09:36
回答 1查看 1.2K关注 0票数 0

我正在将spring从4.3.3升级到5.2.7,我有这样的例外:

异常:

代码语言:javascript
复制
Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'MyBean' defined in com.test: Unsatisfied dependency expressed through method 'MyBean' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} 

代码:

代码语言:javascript
复制
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@SuppressWarnings({ "unchecked" })
public MyBean MyBean(String url,
        String user, String password, String id) {
    return MyBean(url, user, password, id,
            new HashMap<String, String>(),false); 
}

PS 1:我使用context.getBean和args来插入我的bean PS 2:我在应用程序的启动时面临这个问题,即使我在启动时没有使用bean (我使用@Scope("prototype")来插入这个bean,无论何时它被调用) PS 3:我对Spring4.3.3

没有问题

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-04 14:31:18

这可能是因为Spring5.x.x版本有一个悬而未决的问题-

https://github.com/spring-projects/spring-framework/issues/21498

它讨论了特定于5.x.x版本的问题。

从Spring5.0开始,@

可以返回null,其效果是将bean定义留在注册表中,但使值不可自动。但是,如果有另一个相同类型的bean不是null,那么它就不会成为自动的。也许应该这样?Spring的异常没有提到任何bean的存在( null或null )

尝试将字段标记为可选字段,以便在启动时不会失败。

代码语言:javascript
复制
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@SuppressWarnings({ "unchecked" })
public Optional<MyBean> MyBean(Optional<String> url,
        Optional<String> user, Optional<String> password, Optional<String> id) {
    if(url.isEmpty() && user.isEmpty() && password.isEmpty() && id.isEmpty()) {
     return Optional.empty();
    } 
    return Optional.of(new MyBean(url, user, password, id,
            new HashMap<String, String>(),false)); 
}

更新1

我认为这更容易解决。Spring5.0添加了Nullable注释,可能他们只为这种场景添加了这个注释。

API文档链接- https://docs.spring.io/spring/docs/5.0.0.RC1_to_5.0.0.RC2/Spring%20Framework%205.0.0.RC2/org/springframework/lang/Nullable.html

一种常见的Spring注释,用于声明在某些情况下带注释的参数或返回值可以为空。

因此,所需要的是将参数标记为Nullable并返回类型。

代码语言:javascript
复制
  @Bean
  @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  @SuppressWarnings({ "unchecked" })
  public @Nullable MyBean myBean(@Nullable String url,
                                 @Nullable String user, @Nullable String password, @Nullable String id) {
    if(url == null && user == null && password == null && id == null) {
      return null;
    }
    return new MyBean(url, user, password, id,
            new HashMap<String, String>(),false);
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63246594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档