Skip to content

Commit d3d414c

Browse files
committed
Reject @bean method with void return type
Closes gh-31007
1 parent 3c34e69 commit d3d414c

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

spring-context/src/main/java/org/springframework/context/annotation/BeanMethod.java

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,13 @@ final class BeanMethod extends ConfigurationMethod {
4242

4343
@Override
4444
public void validate(ProblemReporter problemReporter) {
45+
if ("void".equals(getMetadata().getReturnTypeName())) {
46+
// declared as void: potential misuse of @Bean, maybe meant as init method instead?
47+
problemReporter.error(new VoidDeclaredMethodError());
48+
}
49+
4550
if (getMetadata().isStatic()) {
46-
// static @Bean methods have no constraints to validate -> return immediately
51+
// static @Bean methods have no further constraints to validate -> return immediately
4752
return;
4853
}
4954

@@ -71,6 +76,15 @@ public String toString() {
7176
}
7277

7378

79+
private class VoidDeclaredMethodError extends Problem {
80+
81+
VoidDeclaredMethodError() {
82+
super("@Bean method '%s' must not be declared as void; change the method's return type or its annotation."
83+
.formatted(getMetadata().getMethodName()), getResourceLocation());
84+
}
85+
}
86+
87+
7488
private class NonOverridableMethodError extends Problem {
7589

7690
NonOverridableMethodError() {

spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2022 the original author or authors.
2+
* Copyright 2002-2023 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.
@@ -143,6 +143,12 @@ void finalBeanMethod() {
143143
initBeanFactory(ConfigWithFinalBean.class));
144144
}
145145

146+
@Test // gh-31007
147+
void voidBeanMethod() {
148+
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
149+
initBeanFactory(ConfigWithVoidBean.class));
150+
}
151+
146152
@Test
147153
void simplestPossibleConfig() {
148154
BeanFactory factory = initBeanFactory(SimplestPossibleConfig.class);
@@ -432,6 +438,14 @@ static class ConfigWithFinalBean {
432438
}
433439

434440

441+
@Configuration
442+
static class ConfigWithVoidBean {
443+
444+
public @Bean void testBean() {
445+
}
446+
}
447+
448+
435449
@Configuration
436450
static class SimplestPossibleConfig {
437451

0 commit comments

Comments
 (0)