jeudi 10 septembre 2020

Static method to return a singleton spring bean

Trying to build a task executor app in spring boot. The idea is to design a template to retrieve the default TaskConfig so that executor can just execute it.

@Component
public class TaskExecutor {

private final TaskTemplate taskTemplate;

@Autowired
public TaskExecutor(TaskTemplate taskTemplate) {
    this.taskTemplate=taskTemplate;
}

public void runTask() {
final TaskConfiguration taskConfig = taskTemplate.getTaskConfig("taskName");
  taskConfig.do();
  }
}

@Component
public class TaskTemplate {
private final TaskParam1 taskParam1;
private final TaskParam2 taskParam2;

@Autowired
public TaskTemplate(TaskParam1 taskParam1, TaskParam2 taskParam2) {
    this.taskParam1 = taskParam1;
    this.taskParam2 = taskParam2;
}

public TaskConfiguration getTaskConfig() {
// Logic to build the task configuration from task template params
 }
}

The problem I see is that the TaskTemplate is coupled with the TaskExecutor (Autowired), which I wish to remove. I wanted to replace it with a static convenient method to return the singleton Template so that I could execute the getTaskConfig with it.

Looking for suggestion to improve upon this.

Thanks

Aucun commentaire:

Enregistrer un commentaire