Until today I was 100 percent sure I don't have to create new instance of class when defining it as a bean. Today I got a bit confused.
I will try to explain part of it in words as I think uploading all the code will make it hard to understand.
I created new REST project using intellij and Spring.
I created new class mapped it and added @RestController
to it.
In this class I added property of another class that I created myself and added @Autowired
to it.
I never created new instance of this class BUT I did add a bean configuration.
until now all worked fine.
I wanted to add ThreadPoolTaskScheduler
logic so I opened new class, added new property ThreadPoolTaskScheduler
and marked it with @Autowired
.
I added a Bean for it:
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
ThreadPoolTaskScheduler threadPoolTaskScheduler
= new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix(
"ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
Now in the main class if I don't send new instance of the class if will throw me null exception.
so this code is working:
public static void main(String[] args) {
SpringApplication.run(RestApiApplication.class, args);
TaskScheduler taskScheduler = new TaskScheduler(new ThreadPoolTaskScheduler());
taskScheduler.setTaskScheduler();
}
and this code is not:
public static void main(String[] args) {
SpringApplication.run(RestApiApplication.class, args);
TaskScheduler taskScheduler = new TaskScheduler();
taskScheduler.setTaskScheduler();
}
this is the TaskScheduler class:
@Controller
public class TaskScheduler {
@Autowired
ThreadPoolTaskScheduler threadPoolTaskScheduler;
TaskScheduler(){}
TaskScheduler(ThreadPoolTaskScheduler threadPoolTaskScheduler){
this.threadPoolTaskScheduler = threadPoolTaskScheduler;
}
public void setTaskScheduler(){
threadPoolTaskScheduler.schedule(
new ScheduledTask(),
new Date());
}
}
- I can't figure out the reason get NULL for threadPoolTaskScheduler at setTaskScheduler, any idea?
- If I definde TaskScheduler also as a bean it works ok, why do I have to? spring can handle everthing or nothing?
If you want me to add more code just tell me.