我正在将spring从4.3.3升级到5.2.7,我有这样的例外:
异常:
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: {} 代码:
@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
没有问题
发布于 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 )
尝试将字段标记为可选字段,以便在启动时不会失败。
@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注释,可能他们只为这种场景添加了这个注释。
一种常见的Spring注释,用于声明在某些情况下带注释的参数或返回值可以为空。
因此,所需要的是将参数标记为Nullable并返回类型。
@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);
}https://stackoverflow.com/questions/63246594
复制相似问题