0

I have the following Spring scheduler configuration class:

@Configuration
@EnableScheduling
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SchedulerConfig implements SchedulingConfigurer {

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    taskRegistrar.setScheduler(taskScheduler());
  }

  @Bean
  public TaskScheduler taskScheduler() {
    TaskScheduler taskScheduler= new ConcurrentTaskScheduler();
    return taskScheduler;
  }
}

and I have an another class

public class Sample 
{
  @Autowired
  TaskScheduler taskScheduler
}

Is the taskScheduler object from "Sample" class different from the object setup at "taskRegistrar.setScheduler(taskScheduler());" class? Is "taskScheduler() call returning different instance than the object injected in the "Sample" class?

If so, how do we ensure there is only one instance of of TaskScheduler in the project? I tried Singleton scope, but still not sure if it ensures same object.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Alagesan Palani
  • 1,984
  • 4
  • 28
  • 53

1 Answers1

1

Spring beans are singletons and you can inject them in other classes using @Autowired or by constructor as you are doing and spring ensures that is always the same instance the one that is injected, so answering your question yes, It is singleton.

As you can see in the documentation: https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html?

The singleton scope is the default scope in Spring.

JArgente
  • 2,239
  • 1
  • 9
  • 11
  • Thanks for the reply. just to confirm. is taskScheduler() instance from "SchedulerConfig" and taskScheduler instance from "Sample" class same. ? is there only one instance of Taskscheduler in the project? – Alagesan Palani Feb 15 '21 at 07:58
  • Yes, both are the same instance. If you dont change the scope of the bean by default is singleton, so there is only one instance of this type in the spring context – JArgente Feb 15 '21 at 08:07