Skip to content

Commit 21cb9e8

Browse files
committed
Translate NullBean result to null for lookup method with bean name
Closes gh-25806
1 parent c83f6ad commit 21cb9e8

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

spring-beans/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2019 the original author or authors.
2+
* Copyright 2002-2020 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.
@@ -238,8 +238,10 @@ public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp
238238
Assert.state(lo != null, "LookupOverride not found");
239239
Object[] argsToUse = (args.length > 0 ? args : null); // if no-arg, don't insist on args at all
240240
if (StringUtils.hasText(lo.getBeanName())) {
241-
return (argsToUse != null ? this.owner.getBean(lo.getBeanName(), argsToUse) :
241+
Object bean = (argsToUse != null ? this.owner.getBean(lo.getBeanName(), argsToUse) :
242242
this.owner.getBean(lo.getBeanName()));
243+
// Detect package-protected NullBean instance through equals(null) check
244+
return (bean.equals(null) ? null : bean);
243245
}
244246
else {
245247
return (argsToUse != null ? this.owner.getBean(method.getReturnType(), argsToUse) :

spring-beans/src/test/java/org/springframework/beans/factory/annotation/LookupAnnotationTests.java

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2019 the original author or authors.
2+
* Copyright 2002-2020 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.
@@ -108,10 +108,23 @@ public void testWithEarlyInjection() {
108108
assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean);
109109
}
110110

111+
@Test // gh-25806
112+
public void testWithNullBean() {
113+
RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class, () -> null);
114+
tbd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
115+
beanFactory.registerBeanDefinition("testBean", tbd);
116+
117+
AbstractBean bean = beanFactory.getBean("beanConsumer", BeanConsumer.class).abstractBean;
118+
assertThat(bean).isNotNull();
119+
Object expected = bean.get();
120+
assertThat(expected).isNull();
121+
assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean);
122+
}
123+
111124

112125
public static abstract class AbstractBean {
113126

114-
@Lookup
127+
@Lookup("testBean")
115128
public abstract TestBean get();
116129

117130
@Lookup

0 commit comments

Comments
 (0)