Well, this is the classical Why is my Spring @Autowired
field null
case. You create the S3Thread
instance by yourself, and thus, no beans are injected into it.
Considering you're trying to just do something in a separate thread, you can consider using @Async
:
@Async
public void updateAutomationConfiguration() {
Automation config = new Automation("user1", "success");
automationService.updateAutomation(config);
}
Notes:
- You have to add the
@EnableAsync
annotation to any configuration class (eg. your main class) to make this work.
- Spring uses proxying by default, which means that you can't add this
updateAutomationConfiguration()
class to your controller itself. Direct calls to methods within the same bean bypass the proxied logic. The solution is to put this method in a separate bean which can be autowired and invoked from within the controller. I've provided more detailed answers about alternative solutions in this answer.
Spring also has a getting started guide for creating asynchronous methods.
Alternatively, there are also some ways to execute asynchronous calls within controllers, for example by using CompletableFuture
within a controller:
@PutMapping("/automation/configuration")
public CompletableFuture<String> updateAutomationConfiguration() {
return CompletableFuture.supplyAsync(() -> {
Automation config = new Automation("user1", "success");
return automationService.updateAutomation(config);
});
}
Related: How to create a non-blocking @RestController
webservice in Spring?