Repository navigation
Description
There are a number of places where Framework iterates over a class's methods. This issue is intended to identify the places where the iteration is unnecessary and can be eliminated. ReflectionUtils keeps a per-Class cache of declared methods. To provide any significant benefit it will be necessary to eliminate all calls to ReflectionUtils for a particular class. It's not yet known if this is possible.
AbstractAutowireCapableBeanFactory.determineTargetType uses the bean definition's targetType to short-circuit type determination. When a bean is defined by ConfigurationClassBeanDefinitionReader processing a @Bean method, this type information is available but it is not used. If the metadata for the @Bean method is StandardMethodMetadata, the target type of the definition is available from the introspected method's return type. Otherwise, the name of the target type is available from MethodMetadata.getReturnTypeName(). It appears to be possible for this type name to be stored in the definition and then be used to load the named class when getTargetType() is invoked.
When processing a ConfigurationClassBeanDefinition, ConstructorResolver.instantiateUsingFactoryMethod calls ReflectionUtils.getAllDeclaredMethods to find the Method for the @Bean method for which the bean definition was created. When the definition was created from StandardMethodMetadata, I think this method will already have been available and could, perhaps, have been stored in the definition's resolvedConstructorOrFactoryMethod field. For ASM-based metadata, the method's name is available and, with some changes to the metadata, it looks like its parameter types could be too. This may then allow the method to be identified directly without the need to iterate over all methods.
Activity
wilkinsona commentedon Feb 15, 2019
With some hacks in place to avoid the two occurrences described above, and with
@Configurationclass proxying disabled, we reach code that's iterating over the methods looking for annotations:CommonAnnotationBeanPostProcessor(and its super-classInitDestroyAnnotationBeanPostProcessor)AutowiredAnnotationBeanPostProcessorfor honouring@AutowiredAutowiredAnnotationBeanPostProcessoragain when looking for@Lookupmethods while determining constructors from bean post-processorsConfigurationPropertiesBindingPostProcessorfinding the bean's factory method to look for@ConfigurationPropertiesannotationAfter these we move on to proxy creation in
InfrastructureAdvisorAutoProxyCreator. There's a single advisor in the case I'm currently looking at, namelyBeanFactoryTransactionAttributeSourceAdvisor. This results in iteration over all of the class's methods, looking for one to which the advice can apply. In this case it's looking for@Transactionalso it's an annotation search again, but not as easy to avoid with an index due to the use of method-based matching.Last of all (in the case I'm currently looking at) we get to
EventListenerMethodProcessorlooking for@EventListenermethods. I'm cautiously optimistic that, with some changes in place to avoid the two occurrences described above and an annotation index, we could avoid all reflection over the methods of certain beans. The ability to opt out of configuration class proxying would increase the number of beans that falls into that category.wilkinsona commentedon Feb 18, 2019
Somewhat related to this, I think there is some benefit in making the factory method that's used to create something defined using
@Beanmore readily available.Boot supports the use of
@ConfigurationPropertieson a@Beanmethod, predominantly to support binding to third-party classes when annotating the class itself with@ConfigurationPropertiesisn't possible. Boot has a class,ConfigurationBeanFactoryMetadata, that performs factory method discovery and caches its results. It would be more robust if the factoryMethodwas directly available via the bean definition rather than having to duplicate the reflective search over the factory class's methods to find the factory method.Please let me know if you'd prefer for this piece to be tracked as a separate issue.
jhoeller commentedon Mar 11, 2019
I'm about to commit an initial revision: a mechanism for bypassing method traversal for annotation introspection if possible. The
isCandidateClassmechanism is consistently used for a bypass check before method traversal attempts now. While by default this is only bypassing standard java types (which never have annotations that we consider searchable), the same mechanism can be used with index metadata which indicates non-presence of certain annotations. All it takes is a more sophisticated implementation ofAnnotationUtils.isCandidateClass(clazz, annotationName)which indicates non-presence of a specific annotation in a class (and its superclasses/interfaces); we'll revise that as part of our indexer efforts, ideally through a programmatic registration mechanism populated from index metadata on startup.As for factory method resolution, I'll tackle this in a separate revision. An initial prototype works reasonably well. We just need to handle the rare cases of
@Beanmethod overloads properly where we still need to apply our construction resolution algorithm against all candidate factory methods.Bypass method traversal for annotation introspection if possible
jhoeller commentedon Mar 11, 2019
FWIW, that remaining part is only really trying to avoid full method traversal for pre-identified
@Configurationclasses... where the methods might have been traversed already, e.g. for finding@Beanmethods with standard annotation metadata to begin with. It's worth addressing for the component scan case where the initial@Beanmetadata comes from ASM but probably won't make much difference forClass-registered beans where the declared methods cache is populated already.jhoeller commentedon Mar 12, 2019
I'm about to wrap up the factory method part: Aside from some general optimizations (like consistently ignoring
java.lang.Objectmethods), we're preserving an existing factoryMethodhandle as far as possible. For the classpath scanning case where we only have ASM metadata initially, we're resolving theMethodonce... either on type matching or on actual construction, never twice. This can be bypassed by calling the newsetResolvedFactoryMethodmethod onRootBeanDefinitionafter the initial scan.FWIW, for the common ASM case, it's hard to avoid full reflective initialization of the affected
Classsince even a directgetDeclaredMethod(name, paramTypes)call would initialize all declared methods underneath the covers. It doesn't seem too bad to traverse the declared methods once there ourselves since it's at least dealing with a class where we actually know that there are@Beanmethods on it.3 remaining items
jhoeller commentedon Mar 13, 2019
I've pushed a revision which should fix this. Turned out to be as simple as going into our proper exception handling code path even when the arguments remain unresolved for a pre-determined factory method, not just when the factory method itself remains unresolved.
wilkinsona commentedon Mar 13, 2019
Thanks. I'm seeing the same behaviour as 5.1.4 again now.
wilkinsona commentedon Mar 13, 2019
The changes here haven't gone quite far enough to allow me to address this scenario from the list above:
I have a bean with ASM-based metadata that's been instantiated by
ConstructorResolver. In doing so, it has setresolvedConstructorOrFactoryMethodon the definition. It's package-private so I can't get at its value andfactoryMethodToIntrospectremainsnull. As a result, we have to fall back to iterating over the methods of the bean's factory class to find the@Beanmethod and determine if it's annotated with@ConfigurationProperties.Would it be possible to somehow expose
resolvedConstructorOrFactoryMethodvia public API? Or, to describe the problem without suggesting a solution, would it be possible for Framework to provide an API that, when given a bean name or a bean definition, returns the@Beanmethod that created the bean ornullif it was created via a different mechanism.jhoeller commentedon Mar 13, 2019
Hmm we have
RootBeanDefinition.getResolvedFactoryMethod()already... Maybe we should just make sure that it is consistently populated, i.e. ifresolvedConstructorOrFactoryMethodis set to a method, the same method should be exposed throughgetResolvedFactoryMethod().wilkinsona commentedon Mar 13, 2019
I wasn't sure if
resolvedConstructorOrFactoryMethodandfactoryMethodToIntrospectmay be subtly different. For the specific purpose of finding the@Beanmethod with@ConfigurationPropertieson it, there's no differences as far as I can tell so it would work nicely in this case at least.jhoeller commentedon Mar 13, 2019
On review, I can't find a code path where
resolvedConstructorOrFactoryMethodis set butfactoryMethodToIntrospectis not. Could you step through that particular construction step to find out howresolvedConstructorOrFactoryMethodis being set?wilkinsona commentedon Mar 13, 2019
Sorry, it looks like there's some ordering in play here.
Looking in the debugger,
resolvedConstructorOrFactoryMethodis set here:spring-framework/spring-beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java
Line 464 in 840d80b
By that point,
factoryMethodToIntrospectwas also non-null.We have a BFPP at the moment and when it's called beans with standard annotation metadata have
factoryMethodToIntrospectset but theresolvedConstructorOrFactoryMethodas that resolution hasn't taken place.It looks like we need to move away from using a BFPP. I think that's fine as I can't see too much value in it as we only need the information that it provides once the beans have been created and we can get that in a more straightforward manner now I believe.
wilkinsona commentedon Mar 13, 2019
Thanks for bearing with me. I think I've found the source of my confusion.
When the bean is being created, the bean definition has been merged and is not the same as the definition that's returned when asking the bean factory for a definition by name. As a result, the factory method information is not available when examining the definition that's returned by the bean factory.
jhoeller commentedon Mar 13, 2019
Merging preserves the
factoryMethodToIntrospect, so should carry over aMethodset early. As for programmatically introspecting it, for guaranteed access to the factory's resolution efforts, you'd have to callConfigurableBeanFactory.getMergedBeanDefinition... at a late enough point.Or are we suffering from early merging here where the merge result is not preserved since the configuration isn't frozen yet?
wilkinsona commentedon Mar 13, 2019
In the case I'm looking at, it's being set after the merging. Specifically, it's happening here:
spring-framework/spring-beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java
Line 613 in 9cf9d0f
That's what I needed. Thanks. I've reworked the original code so that it's no longer a BFPP and we now just look up the information on demand. This means that the earliest that it will happen is in bean post-processing by which time the bean has been instantiated and the merged bean definition has the outcome of the resolution efforts.
sbrannen commentedon Mar 14, 2019
FYI: the discussions around finding annotations on
@Beanmethods are directly related to #22541.@mdeinum, you may want to follow along here.
sbrannen commentedon Mar 14, 2019
ConfigurationBeanFactoryMetadatadoesn't properly track overloaded@Beanmethods within a single@Configurationclass -- right?Not that people often overload their
@Beanmethods, but it is supported, and at a glance it looks likeConfigurationBeanFactoryMetadataonly considers the method names, ignoring the parameter lists.wilkinsona commentedon Mar 14, 2019
Things have changed quite a bit in 2.2. We're now using the resolved factory method that's cached on the definition so overriding should not cause any problems. That said, please don't point people to
ConfigurationBeanFactoryMetadata. While it's currently public we would prefer that it, or at least as much as possible of it, is not.[WIP] Update prototype due to changes in spring-projectsgh-22420
Early resolution of unique factory methods in configuration classes