spring-projects/spring-ai · error · IllegalArgumentException

Bean must not be null

Error message

Bean must not be null

What it means

Thrown by Builder.validate() in AbstractMcpElicitationMethodCallback when the target bean (the instance holding the annotated handler method) is null at build() time. The callback invokes method on this bean, so it must be a live instance.

Source

Thrown at mcp/mcp-annotations/src/main/java/org/springframework/ai/mcp/annotation/method/elicitation/AbstractMcpElicitationMethodCallback.java:239

		 * @param elicitation The elicitation annotation
		 * @return This builder
		 */
		@SuppressWarnings("unchecked")
		public T elicitation(McpElicitation elicitation) {
			// No additional configuration needed from the annotation at this time
			return (T) this;
		}

		/**
		 * Validate the builder state.
		 * @throws IllegalArgumentException if the builder state is invalid
		 */
		protected void validate() {
			if (this.method == null) {
				throw new IllegalArgumentException("Method must not be null");
			}
			if (this.bean == null) {
				throw new IllegalArgumentException("Bean must not be null");
			}
		}

		/**
		 * Build the callback.
		 * @return A new callback instance
		 */
		public abstract R build();

	}

}

View on GitHub (pinned to 98a7beda4f)

Solutions

  1. Pass a non-null handler instance with .bean(handlerInstance)
  2. Verify the Spring bean actually exists in the context before registering (context.getBean returns non-null)
  3. Ensure bean initialization order: register elicitation callbacks after the handler bean is constructed

Example fix

// before
Object handler = context.getBean("elicitationHandler"); // resolves to null
builder.method(method).bean(handler).build();

// after
MyHandler handler = context.getBean(MyHandler.class);
if (handler != null) {
    builder.method(method).bean(handler).build();
}
Defensive patterns

Strategy: validation

Validate before calling

Objects.requireNonNull(handlerBean, "bean must be set before build()");
builder.method(method).bean(handlerBean).build();

Type guard

boolean canRegister(Object handler) { return handler != null; }

Prevention

When it happens

Trigger: Calling build() on a Sync/AsyncMcpElicitationMethodCallback builder with .method(...) set but no .bean(instance) — e.g. passing a null Spring bean or forgetting the bean call.

Common situations: Manual registration where the handler bean is fetched from the application context and the lookup returned null (bean not yet created, wrong name, or @Lazy bean accessed too early).

Related errors


AI-assisted analysis of spring-projects/spring-ai@98a7beda4f (2026-09-11). Data as JSON: /api/errors/27d3b1a7fa7bcd9c. Report an issue: GitHub.