gpt4 book ai didi

java - 在 SpringBootApplication 类中使用服务会抛出 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 20:55:16 25 4
gpt4 key购买 nike

我对 SpringBoot 还很陌生。我创建了一个带有服务类的示例应用程序。

下面是我的SpringBootApplication

@SpringBootApplication
public class SampleApplication {

@Autowired
static AWSService awsService;

public static void main(String[] args) {

SpringApplication.run(SampleApplication.class, args);
awsService.getCertificate(); // Getting an NPE at this point

}

}

AWSService

@Service
public class AWSService {

public AWSService() {

}

private final Log log = new Log(getClass().getSimpleName());

public void getCertificate() {
String accessKey="";
String secretKey="";
try {
Scanner awsCredentials = new Scanner(new File(Constants.AWS_CREDENTIALS));
accessKey=awsCredentials.next();
secretKey=awsCredentials.next();
} catch (FileNotFoundException e) {
e.printStackTrace();
log.error(e.getMessage());
}
BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKey,secretKey);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(
new AWSStaticCredentialsProvider(basicAWSCredentials)).build();
S3Object s3object = s3Client.getObject(
new GetObjectRequest(Constants.S3_BUCKET_NAME, Constants.S3_KEY_NAME));
String temporaryCertificatePath = storeCertificate(s3object);
Constants.setKeyStoreFile(temporaryCertificatePath);
}

private String storeCertificate(S3Object s3Object) {
try {
File certificate = File.createTempFile("signingKey",".p12");
OutputStream outputStream = new FileOutputStream(certificate);
byte buffer [] = IOUtils.toByteArray(s3Object.getObjectContent());
outputStream.write(buffer);
certificate.deleteOnExit();
return certificate.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
log.error(e.getMessage());
}
return null;
}
}

以下是我收到的错误

Exception in thread "main" java.lang.NullPointerException
2017-02-27 13:24:04.023 at in.juspay.SampleApplication.main(SampleApplication.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
INFO at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
798 at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

我在应用程序类中Autowired服务,但我收到了NullPointerException。如果我正确理解 Spring 的 @Service ,则 @Autowire 应该负责对象的初始化。那么为什么我会在那时获得 NPE 呢?

最佳答案

您无法 Autowiring 静态字段。使用应用程序上下文来访问它。

Can you use @Autowired with static fields?

关于java - 在 SpringBootApplication 类中使用服务会抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42480601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com