amy
amy

Reputation: 297

Should we use @Component annotation on the class just to document/indicate that it's a Bean?

Even when we create the Beans in a Spring configuration class, I feel it is still useful to use @Component annotation on the class just to document/indicate that it's a Bean. Is it a good idea? Can there be any other issue that Spring will find the same bean defined in two different ways?

Upvotes: 0

Views: 157

Answers (1)

Andrii Vdovychenko
Andrii Vdovychenko

Reputation: 300

It is bad practice to create two beans from one class...

@Component
class SimpleComponent {
}

@Bean
public SimpleComponent simpleComponentBean(){
    new SimpleComponent();
}

By default if we use @Component spring creates bean with name of class, but starts with small letter simpleComponent, if we use @Bean it takes method name and create bean with name simpleComponentBean and we have duplicated beans... If we have method name the same, as component class name, spring replace one of them and we can Inject unexpected bean.

PS: intellij idea enterprise - correct indicate about all beans.

Upvotes: 1

Related Questions