Skip to content
Advertisement

what will happen if we didn’t define @Bean under @Configuration class in spring boot

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?

Advertisement

Answer

@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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement