我是Spring Boot的新手。有谁知道如何在主类中调用amazonSQSClient()方法?

@Configuration
public class AWSConfiguration {
    @Value("${aws.access.key.encrypted}")
    private String amazonAWSAccessKey;

    @Value("${aws.secret.key.encrypted}")
    private String amazonAWSSecretKey;

    @Value("${aws.region.encrypted}")
    private String amazonAWSRegion;

    @Bean
    public AmazonSQS amazonSQSClient() {

        AWSCredentials awsCredentials = new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey);
        AmazonSQS client = AmazonSQSClientBuilder.standard()
                .withRegion(amazonAWSRegion)
                .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).build();

        return client;
    }
}

最佳答案

您不需要。这就是使用@Bean批注的要点,Spring会在需要时注入AmazonSQS实例。因此,您可能有一个使用SQS客户端的此类:

@Service
public class QueueService {

    private AmazonSQS amazonSQS;

    @Autowired
    public QueueService(AmazonSQS sqs) {
        this.amazonSQS = sqs;
    }
}


Spring框架足够聪明,可以看出它需要注入AmazonSQS的实例,并通过使用amazonSqsClient批注标记方法@Bean来告诉Spring在需要创建实例时使用该方法。的AmazonSQS

08-06 14:43