AmazonS3变量未能正确自动装配。

huangapple go评论82阅读模式
英文:

AmazonS3 variable is not getting autowired correctly

问题

com.amazonaws.SdkClientException: 无法从链中的任何提供程序加载 AWS 凭据
	at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:131)
	at com.amazonaws.http.AmazonHttpClient$RequestExecutor.getCredentialsFromContext(AmazonHttpClient.java:1119)
	at com.amazonaws.http.AmazonHttpClient$RequestExecutor.runBeforeRequestHandlers(AmazonHttpClient.java:759)
	...

**ApplicationConfiguration.java**
```java
package com.moveinsync.routeconfiguration.application.config;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class ApplicationConfiguration {
    @Value("${aws.routeconfig.accesskey}")
    private String accessKey;
    @Value("${aws.routeconfig.secretkey}")
    private String secretKey;
    @Value("${aws.routeconfig.region}")
    private String awsRegion;
    
    @Bean
    public AmazonS3 initializeAmazonS3(){
        AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
        AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(awsRegion).build();
        return amazonS3;
    }
    
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("routingParameters");
    }
}

AmazonS3Abstraction.java

package com.moveinsync.routeconfiguration.application.services;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import com.moveinsync.routeconfiguration.application.exceptionhandlers.BusinessUnitNotFoundException;
import com.moveinsync.routeconfiguration.application.exceptionhandlers.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Component
public class AmazonS3Abstraction {
    @Autowired
    private AmazonS3 amazonS3;
    @Value("${aws.routeconfig.bucketname}")
    private String bucketName;
    
    @Cacheable("routingParameters")
    public boolean businessUnitExists(String businessUnit) throws BusinessUnitNotFoundException, CustomException {
        try {
            if (amazonS3.listObjectsV2(bucketName, businessUnit).getKeyCount() == 0) {
                throw  new BusinessUnitNotFoundException();
            }
            return true;
        } catch (AmazonS3Exception e) {
            throw new CustomException();
        }
    }
    
    public S3Object getObject(String bucketName, String objectKey) throws CustomException {
        try {
            return amazonS3.getObject(bucketName, objectKey);
        } catch (AmazonS3Exception e) {
            throw new CustomException();
        }
    }
    
    public void putObject(String bucketName, String objectKey, String params) throws CustomException {
        try {
            amazonS3.putObject(bucketName, objectKey, params);
        } catch (AmazonS3Exception e) {
            throw new CustomException();
        }
    }
    
    public CopyObjectResult copyObject(String s1, String s2, String s3, String s4) throws CustomException {
        try {
            return amazonS3.copyObject(s1, s2, s3, s4);
        } catch (AmazonS3Exception e) {
            throw new CustomException();
        }
    }
    
    public ObjectListing listObjects(ListObjectsRequest listObjectsRequest) throws CustomException {
        try {
            return amazonS3.listObjects(listObjectsRequest);
        } catch (AmazonS3Exception e) {
            throw new CustomException();
        }
    }
}

Stack Trace

com.amazonaws.SdkClientException: 无法从链中的任何提供程序加载 AWS 凭据
	at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:131)
	at com.amazonaws.http.AmazonHttpClient$RequestExecutor.getCredentialsFromContext(AmazonHttpClient.java:1119)
	at com.amazonaws.http.AmazonHttpClient$RequestExecutor.runBeforeRequestHandlers(AmazonHttpClient.java:759)
	...
英文:

I am trying to run a Spring Application which works with AmazonS3 but the amazonS3 variable in AmazonS3Abstraction.java is not getting autowired correctly for some reason. It stays null. It keeps throwing an SDK Client Exception: Unable to load AWS Credentials from any provider in the chain.

I want the variable amazonS3 in AmazonS3Abstraction.java to have the exact same value which is getting returned by the bean, initializaAmazonS3(), in ApplicationConfiguration.java.

I am attaching my code and stack trace below. Please help me out. Feel free to add for more details.

ApplicationConfiguration.java

package com.moveinsync.routeconfiguration.application.config;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class ApplicationConfiguration {
@Value("${aws.routeconfig.accesskey}")
private String accessKey;
@Value("${aws.routeconfig.secretkey}")
private String secretKey;
@Value("${aws.routeconfig.region}")
private String awsRegion;
@Bean
public AmazonS3 initializeAmazonS3(){
AWSCredentials credentials = new BasicAWSCredentials(this.accessKey,this.secretKey);
AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(awsRegion).build();
return amazonS3;
}
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("routingParameters");
}
}

AmazonS3Abstraction.java

package com.moveinsync.routeconfiguration.application.services;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import com.moveinsync.routeconfiguration.application.exceptionhandlers.BusinessUnitNotFoundException;
import com.moveinsync.routeconfiguration.application.exceptionhandlers.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class AmazonS3Abstraction {
@Autowired
private AmazonS3 amazonS3;
@Value("${aws.routeconfig.bucketname}")
private String bucketName;
@Cacheable("routingParameters")
public boolean businessUnitExists(String businessUnit) throws BusinessUnitNotFoundException, CustomException{
try{
if (amazonS3.listObjectsV2(bucketName, businessUnit).getKeyCount() == 0){
throw  new BusinessUnitNotFoundException();
}
return true;
} catch (AmazonS3Exception e){
throw new CustomException();
}
}
public S3Object getObject(String bucketName, String objectKey) throws CustomException{
try{
return amazonS3.getObject(bucketName, objectKey);
} catch (AmazonS3Exception e){
throw  new CustomException();
}
}
public void putObject(String bucketName, String objectKey, String params) throws CustomException{
try{
amazonS3.putObject(bucketName, objectKey, params);
}catch (AmazonS3Exception e){
throw new CustomException();
}
}
public CopyObjectResult copyObject(String s1, String s2, String s3, String s4) throws CustomException{
try{
return amazonS3.copyObject(s1, s2, s3, s4);
}catch (AmazonS3Exception e){
throw new CustomException();
}
}
public ObjectListing listObjects(ListObjectsRequest listObjectsRequest) throws CustomException{
try{
return amazonS3.listObjects(listObjectsRequest);
} catch (AmazonS3Exception e){
throw new CustomException();
}
}
}

Stack Trace

com.amazonaws.SdkClientException: Unable to load AWS credentials from any provider in the chain
at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:131)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.getCredentialsFromContext(AmazonHttpClient.java:1119)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.runBeforeRequestHandlers(AmazonHttpClient.java:759)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:723)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:716)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4221)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4168)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4162)
at com.amazonaws.services.s3.AmazonS3Client.listObjectsV2(AmazonS3Client.java:861)
at com.amazonaws.services.s3.AmazonS3Client.listObjectsV2(AmazonS3Client.java:833)
at com.moveinsync.routeconfiguration.application.services.AmazonS3Abstraction.businessUnitExists(AmazonS3Abstraction.java:24)
at com.moveinsync.routeconfiguration.application.services.AmazonS3Abstraction$$FastClassBySpringCGLIB$$a941c961.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.cache.interceptor.CacheInterceptor.lambda$invoke$0(CacheInterceptor.java:53)
at org.springframework.cache.interceptor.CacheAspectSupport.invokeOperation(CacheAspectSupport.java:366)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:421)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:346)
at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.moveinsync.routeconfiguration.application.services.AmazonS3Abstraction$$EnhancerBySpringCGLIB$$a1dd8a75.businessUnitExists(<generated>)
at com.moveinsync.routeconfiguration.application.services.RouteConfigurationServiceAmazonS3Impl.getRoutingParameters(RouteConfigurationServiceAmazonS3Impl.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.cache.interceptor.CacheInterceptor.lambda$invoke$0(CacheInterceptor.java:53)
at org.springframework.cache.interceptor.CacheAspectSupport.invokeOperation(CacheAspectSupport.java:366)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:421)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:346)
at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy78.getRoutingParameters(Unknown Source)
at com.moveinsync.routeconfiguration.application.controllers.RouteConfigurationController.getConfiguration(RouteConfigurationController.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

答案1

得分: 2

你可能想尝试通过将bean名称设置为"amazonS3"来解决此问题。

    @Bean
    public AmazonS3 initializeAmazonS3(){

其次,您不必自己创建S3客户端bean。只要在类路径中具有Spring Cloud AWS,并提供AWS配置,系统会自动为您创建客户端。

请参考此部分【配置凭据】。

  [配置凭据]: https://cloud.spring.io/spring-cloud-aws/spring-cloud-aws.html#_configuring_credentials
英文:

You might want to try by giving the bean name as "amazonS3". This seems to be an issue.

@Bean
public AmazonS3 initializeAmazonS3(){

Second, you don't have to create an S3 client bean yourself. Having Spring Cloud AWS on the classpath and providing AWS configurations will auto-create the client for you.

Refer to this section Configurating Credentials

huangapple
  • 本文由 发表于 2020年10月13日 18:45:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/64333710.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定