sofaboot3.1 启动报错,Failed to resolve @SofaService on @Bean-method({}) in {}
private void generateSofaServiceDefinitionOnMethod(String beanId,
AnnotatedBeanDefinition beanDefinition,
ConfigurableListableBeanFactory beanFactory) {
Class<?> returnType;
Class<?> declaringClass;
Method method = null;
MethodMetadata methodMetadata = beanDefinition.getFactoryMethodMetadata();
try {
returnType = ClassUtils.forName(methodMetadata.getReturnTypeName(), null);
declaringClass = ClassUtils.forName(methodMetadata.getDeclaringClassName(), null);
for (Method m : declaringClass.getDeclaredMethods()) {
Bean bean = m.getAnnotation(Bean.class);
Set<String> beanNames = Stream.of(m.getName()).collect(Collectors.toSet());
if (bean != null) {
beanNames.addAll(Arrays.asList(bean.name()));
beanNames.addAll(Arrays.asList(bean.value()));
}
if (!beanNames.contains(beanId)) {
continue;
}
if (method != null) {
throw new IllegalStateException("multi @Bean-method with same name in "
+ declaringClass.getCanonicalName());
}
method = m;
}
} catch (Throwable throwable) {
SofaLogger.error(throwable, "Failed to resolve @SofaService on @Bean-method({}) in {}",
beanId, methodMetadata.getDeclaringClassName());
throw new FatalBeanException("Failed to resolve @SofaService on method", throwable);
}
if (method != null) {
SofaService sofaServiceAnnotation = method.getAnnotation(SofaService.class);
if (sofaServiceAnnotation == null) {
sofaServiceAnnotation = returnType.getAnnotation(SofaService.class);
}
generateSofaServiceDefinition(beanId, sofaServiceAnnotation, returnType,
beanDefinition, beanFactory);
generateSofaReferenceDefinition(beanId, method, beanFactory);
}
}
在引入了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
在解析org.springframework.boot.autoconfigure.amqp.RabbitAnnotationDrivenConfiguration这个类时,generateSofaServiceDefinitionOnMethod会在解析RabbitAnnotationDrivenConfiguration中的 @Bean 类时 throw new IllegalStateException("multi @Bean-method with same name in "的错误,看了下业务逻辑,除非我不使用AMQP-STARTER去除自动装载,要不一定会报错启动不了项目
这个似乎是因为静态扫描遇到了多个同名 @Bean 配置了不同的 @Conditional 的情况。这里不知道能否直接通过 AnnotatedTypeMetadata 拿到注解信息,但是似乎不太好拿参数列表。
PS:不是 sofa 维护者,只是补充一个参考。
@ujjboy
@QilongZhang 请教一下,@SofaReference 作为参数注入的这个功能,有尝试过使用 AutowireCandidateResolver 么?
看上去直接在 BeanDefinition 拿到调用方法和参数比较困难(小概率能得到 StandardMethodMetadata),用这个实现注入相关的逻辑似乎更简单(在注入时被调用,能拿到方法参数类型和注解,返回值会被注入到方法中),就是不知道实现上是否会有什么坑。
@ScienJus 感谢交流,AutowireCandidateResovler 没有试过,我研究下呢。 目前 @SofaReference 实现注入的逻辑是通过 com.alipay.sofa.runtime.spring.bean.SofaParameterNameDiscoverer 这个类扩展实现的,应该是不依赖 StandardMethodMetadata 。
@QilongZhang 是这样,我今天看这个 issue 时,觉得报错的原因应该是 ServiceBeanFactoryPostProcessor 通过 BeanDefinition 的名称寻找其 Factory Method 时,因为可能会出现同名方法配置了不同 Conditions 或是不同参数,导致反射扫描并不能直接找到这个方法。
然后我看了下获取 Factory Method 主要是为了创建 @SofaService 的 Bean 时能够拿到注解,以及寻找参数有 @SofaReference 的 Factory Method 并进行注入(通过创建另一个 depends on 的 BeanDefinition)。
前者理论上不复杂,BeanDefinition 应该有完整的注解元数据,可以直接拿来使用。而后者因为要扫描参数并获取其 @SofaReference,而直接在 BeanDefinition 中获取方法参数似乎是很复杂的事情(除非 MetaData 是一个 StandardMethodMetadata)。
所以我觉得可以尝试 AutowireCandidateResovler 看看是否能完成这个行为,每一个需要注入的对象(无论是 @Bean 的参数、还是 @Autowired 的字段、方法、构造函数)理论上都会走这个逻辑,在这里解析特殊注解并返回 Reference 对象也许可行。
也有可能是我理解错了= =,无论如何希望能有一些参考价值。
@ScienJus AutowireCandidateResolver 应该也可以用于解决 @SofaReference 注入,当前的注入方案是通过 SofaParameterNameDiscoverer 这个类,修改参数名称做到的,感谢建议,不考虑其他因素,AutowireCandidateResovler 实现上应该会简单点。
这个 issue 的报错的原因是,在解析 method 上的 SofaService 注解时,根据当前的 BeanDefinition 没有找到合适的手段确定唯一生成该 BeanDefinition 的 Method,请问这块你有什么好的建议。
@QilongZhang 我觉得仅靠方法名扫描找到 Factory Method 应该是没办法处理好所有情况的,我个人可能会试试看:
Factory Method 的第一个用途是获取方法的 @SofaService,是否能直接使用注解元数据去获取?例如:
methodMetadata.getAnnotationAttributes(SofaService.class.getName());
Factory Method 的第二个用途是获取方法参数,获取参数的 @SofaReference,这个不获取到原生方法做不到,而 MethodMetadata 的两个实现里,只有 StandardMethodMetadata 能够获取到原生方法,MethodMetadataReadingVisitor 获取不到,而 debug 了一下,似乎大部分都是 MethodMetadataReadingVisitor,所以我觉得很难做到。
我更倾向于把第二种用途也归类为一个注入问题,并尝试用用 AutowireCandidateResolver 在注入时才去创建,而不是在 BeanDefinition 时去创建,有点像 ReferenceAnnotationBeanPostProcessor 但是能覆盖到所有注入情况。不确定这样一定可行,是否会有一些强依赖 BeanDefinition 的配置或是加载顺序?我可以先试试。
Demo 大概是:
public class SofaReferenceAutowireCandidateResolver implements AutowireCandidateResolver {
private ConfigurableApplicationContext applicationContext;
private AutowireCandidateResolver delegate;
private SofaRuntimeContext sofaRuntimeContext;
private BindingConverterFactory bindingConverterFactory;
private BindingAdapterFactory bindingAdapterFactory;
public SofaReferenceAutowireCandidateResolver(
ConfigurableApplicationContext applicationContext,
AutowireCandidateResolver delegate,
SofaRuntimeContext sofaRuntimeContext,
BindingConverterFactory bindingConverterFactory,
BindingAdapterFactory bindingAdapterFactory) {
this.applicationContext = applicationContext;
this.delegate = delegate;
this.sofaRuntimeContext = sofaRuntimeContext;
this.bindingConverterFactory = bindingConverterFactory;
this.bindingAdapterFactory = bindingAdapterFactory;
}
@Override
public Object getSuggestedValue(DependencyDescriptor descriptor) {
SofaReference sofaReference = descriptor.getAnnotation(SofaReference.class);
if (sofaReference == null) {
return delegate.getSuggestedValue(descriptor);
}
// Copy from ReferenceAnnotationBeanPostProcessor
return createReferenceProxy(sofaReference, descriptor.getDependencyType());
}
}
运行时大概是:


不知道能否满足需求以及覆盖到所有情况…
@ScienJus 当前的方案使用既有的 BeanDefinition 解析对应的 FactoryMethod,可能不是一个优雅的方案,在这个方案下,解析操作比较复杂,直觉上应该发生在 ConfigurationClassBeanDefinition Parser 阶段处理,不知道你怎么看
methodMetadata.getAnnotationAttributes(SofaService.class.getName()); 其实尝试过这样拿,但是因为返回结果是一个 Map 结构,并不是一个直接的 @SofaService 注解类型,对于 RPC 服务来讲,属性太多而且存在嵌套注解,解析繁琐。
另外顺便说一下,为什么会使用 BeanDefiniton 的方式. 我觉得 ConfigurationClass 是代码化的配置,和 Spring xml 类似。因此 Spring Boot 在解析 Configuration Class 时,采用 xml 类似的处理,是直接转换成了 BeanDefinition. 之前的 SOFABoot 版本,xml 配置的 SofaService 和 SofaReference 都是解析成具体的 BeanDefinition, 而注解方式并不会生成对应的 BeanDefinition,而是通过 PostProcessor 处理。为了统一模型,尽量希望能够以 BeanDefinition 方式统一处理。
Demo 大概是:
public class SofaReferenceAutowireCandidateResolver implements AutowireCandidateResolver { private ConfigurableApplicationContext applicationContext; private AutowireCandidateResolver delegate; private SofaRuntimeContext sofaRuntimeContext; private BindingConverterFactory bindingConverterFactory; private BindingAdapterFactory bindingAdapterFactory; public SofaReferenceAutowireCandidateResolver( ConfigurableApplicationContext applicationContext, AutowireCandidateResolver delegate, SofaRuntimeContext sofaRuntimeContext, BindingConverterFactory bindingConverterFactory, BindingAdapterFactory bindingAdapterFactory) { this.applicationContext = applicationContext; this.delegate = delegate; this.sofaRuntimeContext = sofaRuntimeContext; this.bindingConverterFactory = bindingConverterFactory; this.bindingAdapterFactory = bindingAdapterFactory; } @Override public Object getSuggestedValue(DependencyDescriptor descriptor) { SofaReference sofaReference = descriptor.getAnnotation(SofaReference.class); if (sofaReference == null) { return delegate.getSuggestedValue(descriptor); } // Copy from ReferenceAnnotationBeanPostProcessor return createReferenceProxy(sofaReference, descriptor.getDependencyType()); } }运行时大概是:
不知道能否满足需求以及覆盖到所有情况…
感谢 Demo, 用来解决 SofaReference 注入问题是没有问题的。
赞同「在生成 BeanDefinition 时处理差异,在生成 BeanDefinition 之后的逻辑保持统一」。方法的 annotation 是不是强类型这是个小事,可以先忽略。
但是我觉得这也反映了 spring 在解析 BeanDefinition 时,并不一定真正加载了这个类(这就像是 @ConditionalOnClass(xxx.class) 为什么能存在一样?),所以我对能拿到实际方法以及参数并不乐观。
注解形式和 xml 形式的最大一个区别是,xml 的 reference 也是用户自己定义的 BeanDefiniton,而注解现在的做法是分析参数并自动生成,所以如果它像 XML 一样应该是这样定义:
@Bean("sampleService")
@SofaReference
public SampleService sampleService() {
return null;
}
@Bean
public SampleService sampleService(@Qualifier("sampleService") SampleService sampleService) {
return new SampleServiceImpl("test");
}
虽然这样很 ugly,但是在 spring 的支持上就天差地别了…
但是我觉得这也反映了 spring 在解析 BeanDefinition 时,并不一定真正加载了这个类(这就像是 @ConditionalOnClass(xxx.class) 为什么能存在一样?),所以我对能拿到实际方法以及参数并不乐观。
这个或许可以借鉴 Spring Boot 在解析 ConfigurationClassBeanDefinition 过程,这一步好像已经过滤了条件.
考虑和 XML 对应的话,上面贴的 @SofaReference 注解方式严格意义上是这么定义,需要有下面这一段SofaReference声明
@Bean("refId")
@SofaReference(interface={}, uniqueId={})
public SampleService sampleService() {
return null;
}
只是这段代码其实可以省略,因为在参数上使用 @SofaRefernece 注解,即使不存在上述代码,也不会有歧义,对于用户来讲,这段代码是多余的,写起来也如你所说,有点 ugly,虽然这样给我们支持方案增加了难度:)
嗯,也就是 spring 官方的 api 能够比较简单的提供两种方式:
- 让用户手动定义 @SofaReference 的 BeanDefinition。优点是不用再去找方法了,缺点是对用户来说,这是一段 ugly 且无意义的代码
- 注入用 AutowireCandidateResolver 或者 InjectionPoint,spring 保证了所有注入都会调用,且能拿到最重要的参数信息,缺点就是没办法复用已有的 BeanDefinition 逻辑
所以其实想在这两种方式找折中,所以有第三种做法:
- 手动从 Configuration 里通过 @Bean/method name 扫描到对应方法,优点是兼顾了上面两个的缺点,缺点是目前没办法识别唯一方法(因为参数信息丢了,方法签名是不完整的)
考虑到对用户的使用方式来看,1 基本可以排除,2 和 3 对用户暴露的 API 都是相同的,所以就是尽量能以 3 的方式实现,但是也许 2 能够保底。
在真实世界里,通过过滤方法名 + 注解信息是不是也能保证找到唯一方法?虽然 Java 的方法唯一标识是方法名 + 参数,但是对于 Spring 的 Factory Method 来说,是不存在所谓的重载的,理论上同 BeanId 方法只可能存在于不同 Conditional 的情况。
昨晚一直在啃 ConfigurationClassBeanDefinition 在什么场景能解析到原生方法对象(其实也就是我最开始说的 StandardMethodMetadata ),但是实际运行时发现大部分都不是,我再详细看下原因。
嗯,也就是 spring 官方的 api 能够比较简单的提供两种方式:
- 让用户手动定义 @SofaReference 的 BeanDefinition。优点是不用再去找方法了,缺点是对用户来说,这是一段 ugly 且无意义的代码
- 注入用 AutowireCandidateResolver,spring 保证了所有注入都会调用,且能拿到最重要的参数信息,缺点就是没办法复用已有的 BeanDefinition 逻辑
所以其实想在这两种方式找折中,所以有第三种做法:
- 手动从 Configuration 里通过 @Bean/method name 扫描到对应方法,优点是兼顾了上面两个的缺点,缺点是目前没办法识别唯一方法(因为参数信息丢了,方法签名是不完整的)
考虑到对用户的使用方式来看,1 基本可以排除,2 和 3 对用户暴露的 API 都是相同的,所以就是尽量能以 3 的方式实现,但是也许 2 能够保底。
在真实世界里,通过过滤方法名 + 注解信息是不是也能保证找到唯一方法?虽然 Java 的方法唯一标识是方法名 + 参数,但是对于 Spring 的 BeanDefinition 来说,是不存在所谓的重载的,理论上同 BeanId 方法只可能存在于不同 Conditional 的情况。
昨晚一直在啃
ConfigurationClassBeanDefinition在什么场景能解析到原生方法对象(其实也就是我最开始说的StandardMethodMetadata),但是实际运行时发现大部分都不是,我再详细看下原因。
所以采用了第三种方式,担心确实存在同名方法的存在,所以直接抛出错误而不是打印警告日志. 写这块时,发现通过 MethodMetadata 确定不了唯一方法,因此只能通过反射依次判断,不过当时写的判断条件比较简单,如果判断了方法名和返回值,issue 的问题就不会有了,能解决绝大部分问题,毕竟我们通常不会这么写 Bean-Method。
可以一起看下怎么从 ConfigurationClassBeanDefinition 这里入手找到好的解决手段。
所以采用了第三种方式,担心确实存在同名方法的存在,所以直接抛出错误而不是打印警告日志. 写这块时,发现通过 MethodMetadata 确定不了唯一方法,因此只能通过反射依次判断,不过当时写的判断条件比较简单,如果判断了方法名和返回值,issue 的问题就不会有了,能解决绝大部分问题,毕竟我们通常不会这么写 Bean-Method。
嗯,真实世界会比理论简单很多,多一些判断条件(返回值、注解)能够让出现的情况逐渐减少到 0,另一个是这里即使有多个方法,但是如果都没有 @SofaService 和 @SofaReference 就也没必要报错(因为大部分都是 autoconfig)。否则肯定是用户自己定义的 Bean,此时报错用户是可以修改的,应该也是可接受的。
有些偏题= = 小 patch 几点优化都做了应该会好很多,我再看看有没有什么办法能根本的找到方法引用…
@ScienJus
看了 Spring Boot 2.1.0.RELEASE 代码,根据方法名和BeanId可以唯一确定对应的方法,关键方法:
org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader#isOverriddenByExistingDefinition
// Is the existing bean definition one that was created from a configuration class?
// -> allow the current bean method to override, since both are at second-pass level.
// However, if the bean method is an overloaded case on the same configuration class,
// preserve the existing bean definition.
if (existingBeanDef instanceof ConfigurationClassBeanDefinition) {
ConfigurationClassBeanDefinition ccbd = (ConfigurationClassBeanDefinition) existingBeanDef;
return ccbd.getMetadata().getClassName().equals(
beanMethod.getConfigurationClass().getMetadata().getClassName());
}
@QilongZhang 是这样,但是这个只是在多个 @Bean 都成为 ConfigurationClassBeanDefinition 是否覆盖的情况。
现在的逻辑是扫描静态方法,但是静态方法并不一定会成为 ConfigurationClassBeanDefinition,所以我觉得通过匹配所有的 @Condition 注解的元信息 + 方法名,能够找到一定能加载为 ConfigurationClassBeanDefinition 的 Method,然后其第一顺位就是真正的那个 当前拿到的 BeanDefinition?
@ScienJus 突然想到对于 Spring Boot 自身而言,存在同样的问题. 所有的 ConfigurationClassBeanDefinition 其实都是解析成 FactoryBean,在非 StandardMethodMetadata 情况下,Spring Boot 也是只能拿到 factoryMethodName,同样没有办法确定唯一的 Method,因此在创建 Bean 的过程中,同样也是采取模糊查找的方式,而且竟然还有一些策略,比如比价参数个数等。
org.springframework.beans.factory.support.ConstructorResolver#instantiateUsingFactoryMethod
/**
* Sort the given factory methods, preferring public methods and "greedy" ones
* with a maximum of arguments. The result will contain public methods first,
* with decreasing number of arguments, then non-public methods, again with
* decreasing number of arguments.
* @param factoryMethods the factory method array to sort
*/
public static void sortFactoryMethods(Method[] factoryMethods) {
Arrays.sort(factoryMethods, (fm1, fm2) -> {
boolean p1 = Modifier.isPublic(fm1.getModifiers());
boolean p2 = Modifier.isPublic(fm2.getModifiers());
if (p1 != p2) {
return (p1 ? -1 : 1);
}
int c1pl = fm1.getParameterCount();
int c2pl = fm2.getParameterCount();
return (c1pl < c2pl ? 1 : (c1pl > c2pl ? -1 : 0));
});
}
简单写了一个 Demo 确实如此,两个不同 beanId、 factoryMethodName 相同,方法参数类型不同的重载方法生成对应两个 ConfigurationClassBeanDefinition ,最后创建 Bean 逻辑走的是同一个方法。
@ScienJus 尝试扩展 ConfigurationClassBeanDefinition 解析过程,没有找到合适的入口,如果有发现,欢迎告知。
或许优化下现在的过滤条件(也可以参考 Spring Boot 的刷选逻辑)是不那么坏的方案,你说呢:)
@QilongZhang 感谢说明,这个代码看上去很靠谱(证明官方本身就不靠谱),所以在目前的场景下,赞同模糊查询。
如上文所说,这部分逻辑可以优化为:即使模糊查询依旧无法识别出方法,但是如果这些方法本身就没有 @SofaReference 和 @SofaService 就可以直接无视,如果有的话,抛出异常并让用户改为更清晰的声明方式是比上文代码中官方的做法很 make sense 的方案。