Sobes.tech
Junior — Middle

Why is the @Component annotation not allowed for methods in Spring?

sobes.tech AI

Answer from AI

The @Component annotation in Spring is intended for classes and indicates that the class is a Spring component that should be registered as a bean in the application context.

Applying @Component to methods is not allowed because Spring does not create beans from methods, but from classes. For methods that create and return beans, the @Bean annotation is used, usually within a class marked with @Configuration.

Thus:

  • @Component — for classes, so that Spring automatically detects and registers them.
  • @Bean — for methods that return objects to be registered as beans.

An example of correct usage:

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}