Reputation: 561
so usually when we write a class and add @Configuration to the class, we will define bean in that class for example:
@Configuration
public class AppConfig {
@Bean
public DemoClass service()
{
}
}
but we I review some codes, I saw some class didn't define @bean method in inside these class,like:
@Configuration
public class AutoRefreshConfig {
@Scheduled(fixedRate = 60000)
public void update(){
// update something with a fix rate
}
}
so is this correct? actually it works well. but I am wondering what will happen when I start running the project. what kind of behavior of will spring boot act? Is it just like a normal java class?
Upvotes: 0
Views: 1645
Reputation: 1650
@Configuration
is a special type of @Component
where the annotated class can contain bean definitions (using @Bean
). But if it doesn't contain any bean definition, spring does not throw any exception. In fact, the configuration class can still be used as a bean similar to @Component
annotated class and can be autowired in dependent classes.
The code referenced above should really be annotated with @Component
as it does not have bean definition, but since @Configuration
in itself meta-annotated with @Component
, it still works. The code is syntactically correct, but it doesn't follow spring convention.
A @Configuration
is also a @Component
, but vice versa is not true.
Upvotes: 1
Reputation: 69
The @Scheduled
annotation results in Spring creating a TaskScheduler
implementation to execute your provided Runnable
(in this case, the void update()
method). According to the Spring docs:
The 'default' implementation is ThreadPoolTaskScheduler, wrapping a native ScheduledExecutorService and adding extended trigger capabilities.
So to answer your question, Spring ultimately uses your annotation to create a ScheduledExecutorService
, a native executor service in the java.util.concurrent
package, to execute your task at the desired frequency you provided
Upvotes: 1