Skip to content

Commit 2624b90

Browse files
marschallcbeams
authored andcommitted
Avoid NPE in AutowiredAnnotationBeanPostProcessor
Prior to this change, AABPP#determineRequiredStatus never checked the return value of ReflectionUtils#findMethod when searching for a '#required' attribute. This call returns null for annotations such as @Inject, @value and @resource, and subsequently causes a NullPointerException to be thrown when ReflectionUtils#invokeMethod is called. The NPE is caught immediately and #determineRequiredStatus returns defaulting to true, but this this approach is inefficient. It is also problematic for users who have set breakpoints on NPE -- they end up debugging into Spring internals, which is a false positive. This commit checks the return value of of ReflectionUtils#findMethod, and in the case of null, eagerly returns true. There is no change to external behavior, simply a more efficient and debugging-friendly implementation. Existing test cases already cover this change, given that it is purely a refactoring. Issue: SPR-9316
1 parent b50f6e1 commit 2624b90

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2011 the original author or authors.
2+
* Copyright 2002-2012 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -405,10 +405,16 @@ protected <T> Map<String, T> findAutowireCandidates(Class<T> type) throws BeansE
405405
protected boolean determineRequiredStatus(Annotation annotation) {
406406
try {
407407
Method method = ReflectionUtils.findMethod(annotation.annotationType(), this.requiredParameterName);
408+
if (method == null) {
409+
// annotations like @Inject, @Value and @Resource don't have a method
410+
// (attribute) named "required" -> default to required status
411+
return true;
412+
}
408413
return (this.requiredParameterValue == (Boolean) ReflectionUtils.invokeMethod(method, annotation));
409414
}
410415
catch (Exception ex) {
411-
// required by default
416+
// an exception was thrown during reflective invocation of the required
417+
// attribute -> default to required status
412418
return true;
413419
}
414420
}

0 commit comments

Comments
 (0)