You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot部署AWS Lambda遭遇ClassCastException问题求助

Spring Boot 3部署AWS Lambda时ClassCastException问题解决

问题现象

将Spring Boot 3应用部署到AWS Lambda时触发ClassCastException,简化为最基础配置后问题仍存在,本地运行构建的jar包也能复现该异常。尝试使用SpringBootProxyHandlerBuilder初始化上下文,结果依旧。

错误堆栈跟踪

20:47:59.921 [main] INFO com.amazonaws.serverless.proxy.spring.AwsSpringWebRuntimeInitializer -- AWS Environment: {PATH=/Users/gowdagp/anaconda3/condabin:/Users/gowdagp/Desktop/Autodesk/vcpkg:/opt/homebrew/bin:/opt/homebrew/sbin:/Library/Frameworks/Python.framework/Versions/3.12/bin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/Library/Apple/usr/bin:/usr/local/go/bin:/Users/gowdagp/.npm-global/lib/node_modules:/Users/gowdagp/.npm-global/lib/node_modules/yo, MANPATH=/opt/homebrew/share/man::, IJ_RESTARTER_LOG=/Users/gowdagp/Library/Logs/JetBrains/IntelliJIdea2023.3/restarter.log, CONDA_EXE=/Users/gowdagp/anaconda3/bin/conda, JAVA_HOME=/Library/Java/JavaVirtualMachines/zulu-17.jdk/Contents/Home, CONDA_PYTHON_EXE=/Users/gowdagp/anaconda3/bin/python, TERM=xterm-256color, HOMEBREW_PREFIX=/opt/homebrew, COMMAND_MODE=unix2003, artifactory_username=gowdagp, _CE_M=, LOGNAME=gowdagp, HOMEBREW_REPOSITORY=/opt/homebrew, PWD=/Users/gowdagp/Desktop/Personal/FusionDebugging, XPC_SERVICE_NAME=0, JAVA_MAIN_CLASS_8417=com.example.DebuggingApplication, CONDA_SHLVL=0, INFOPATH=/opt/homebrew/share/info:, _=/usr/bin/java, __CFBundleIdentifier=com.jetbrains.intellij, SHELL=/bin/zsh, HOMEBREW_CELLAR=/opt/homebrew/Cellar, OLDPWD=/Users/gowdagp/Desktop/Personal/FusionDebugging, USER=gowdagp, VCPKG_ROOT=/Users/gowdagp/Desktop/Autodesk/vcpkg, TERMINAL_EMULATOR=JetBrains-JediTerm, TMPDIR=/var/folders/8w/733prh7x7m3bh36cnvf_jqvw0000gp/T/, SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.rK4L8CgsUE/Listeners, _CE_CONDA=, XPC_FLAGS=0x0, TERM_SESSION_ID=7bacf5ce-24d6-441d-8be5-1c97a5c5b663, artifactory_password=Pg2451999845#01234567, __CF_USER_TEXT_ENCODING=0x1F6:0x0:0x0, LC_CTYPE=UTF-8, IDEA_INITIAL_DIRECTORY=/, SHLVL=1, HOME=/Users/gowdagp}
20:47:59.927 [main] INFO com.example.DebuggingApplication -- Starting DebuggingApplication using Java 17.0.10 with PID 8417 (/Users/gowdagp/Desktop/Personal/FusionDebugging/build/libs/debugging-service-0.0.1-SNAPSHOT-all.jar started by gowdagp in /Users/gowdagp/Desktop/Personal/FusionDebugging)
20:47:59.927 [main] INFO com.example.DebuggingApplication -- No active profile set, falling back to 1 default profile: "default"
20:48:00.035 [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext -- Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletWebServerFactory' defined in class path resource [org/springframework/cloud/function/serverless/web/ServerlessAutoConfiguration.class]: class org.springframework.context.annotation.AnnotationConfigApplicationContext cannot be cast to class org.springframework.boot.web.context.ConfigurableWebServerApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext and org.springframework.boot.web.context.ConfigurableWebServerApplicationContext are in unnamed module of loader 'app')
20:48:00.036 [main] ERROR org.springframework.boot.SpringApplication -- Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletWebServerFactory' defined in class path resource [org/springframework/cloud/function/serverless/web/ServerlessAutoConfiguration.class]: class org.springframework.context.annotation.AnnotationConfigApplicationContext cannot be cast to class org.springframework.boot.web.context.ConfigurableWebServerApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext and org.springframework.boot.web.context.ConfigurableWebServerApplicationContext are in unnamed module of loader 'app')
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:607)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:975)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:962)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:624)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:334)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1354)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343)
        at com.example.DebuggingApplication.main(DebuggingApplication.java:10)
Caused by: java.lang.ClassCastException: class org.springframework.context.annotation.AnnotationConfigApplicationContext cannot be cast to class org.springframework.boot.web.context.ConfigurableWebServerApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext and org.springframework.boot.web.context.ConfigurableWebServerApplicationContext are in unnamed module of loader 'app')
        at org.springframework.cloud.function.serverless.web.ServerlessAutoConfiguration$ServerlessServletWebServerFactory.setApplicationContext(ServerlessAutoConfiguration.java:91)
        at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:110)
        at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:85)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:422)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600)
        ... 14 common frames omitted

尝试的代码实现

DebuggingApplication.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DebuggingApplication {

    public static void main(String[] args) {
        SpringApplication.run(DebuggingApplication.class, args);
    }

}

StreamLambdaHandler.java

package com.example;

import com.amazonaws.serverless.exceptions.ContainerInitializationException;
import com.amazonaws.serverless.proxy.model.AwsProxyRequest;
import com.amazonaws.serverless.proxy.model.AwsProxyResponse;
import com.amazonaws.serverless.proxy.spring.SpringBootLambdaContainerHandler;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StreamLambdaHandler implements RequestStreamHandler {

    private static final SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
    static {
        try {
            handler= SpringBootLambdaContainerHandler.getAwsProxyHandler(DebuggingApplication.class);
        } catch (ContainerInitializationException e) {
            e.printStackTrace();
            throw new RuntimeException("Could not initialize Spring Boot application", e);
        }
    }

    @Override
    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context)
            throws IOException {
        handler.proxyStream(inputStream, outputStream, context);
    }
}

build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.2.4'
    id 'io.spring.dependency-management' version '1.1.4'
    id 'com.github.johnrengelman.shadow' version '7.1.2'
}

springBoot {
    mainClass.set('com.example.DebuggingApplication')
}

apply from: 'dependencies.gradle'

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(17))
    }
}

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.amazonaws.serverless:aws-serverless-java-container-springboot3:2.0.1'
}


shadowJar {
    archiveBaseName.set('debugging-service')
    archiveVersion.set('0.0.1-SNAPSHOT')
    manifest {
        attributes 'Main-Class': 'com.example.DebuggingApplication'
    }
}

解决方案

问题根源

ServerlessAutoConfiguration(来自Spring Cloud Function)中的ServerlessServletWebServerFactory试图将AWS Lambda容器初始化的AnnotationConfigApplicationContext强制转换为ConfigurableWebServerApplicationContext,但Lambda容器的上下文并不继承该Web上下文类型,导致类型转换异常。

修复步骤

  1. 排除冲突的自动配置类
    修改DebuggingApplication类,在@SpringBootApplication注解中排除ServerlessAutoConfiguration:
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.function.serverless.web.ServerlessAutoConfiguration;

@SpringBootApplication(exclude = {ServerlessAutoConfiguration.class})
public class DebuggingApplication {

    public static void main(String[] args) {
        SpringApplication.run(DebuggingApplication.class, args);
    }

}
  1. 保留Lambda Handler原有逻辑
    AWS Serverless Java Container的SpringBootLambdaContainerHandler已经提供了完整的Spring Boot集成支持,无需依赖Spring Cloud Function的自动配置,保持原有的StreamLambdaHandler代码即可。

  2. 重新构建并验证
    执行./gradlew shadowJar重新构建jar包,本地可通过AWS SAM CLI测试函数,或直接部署到AWS Lambda验证功能正常。

内容的提问来源于stack exchange,提问作者Prajwal Gowda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 21:44:54