3

I'm confused as to a few things in Spring.

First, when would I want to use @Component over an explicit @Configuration class with a @Bean for what would have been a @Component?

The only reason I can think of for using @Component is to save myself the creation of a @Bean method in a @Configuration class. Are there other reasons?

That said, if I am using a @Configuration class it seems like I can hand code the wiring of these beans. IOW, where I did use @Inject on a @Component I can now explicitly specify dependencies in the @Bean constructor (when I create it in my bean method). So when would I want to use @Inject? I feel like I'm going down a rabbit hole here.

Are there any good tutorials or blogs that cover the best practices or rules for making these kinds of decisions?

Thanks

robert_difalco
  • 4,821
  • 4
  • 36
  • 58
  • Please, check this question: http://stackoverflow.com/questions/10604298/spring-component-versus-bean – Almir Campos Mar 07 '14 at 00:42
  • Yeah, that question actually piqued my interest. If that is true why would one want to use Component over Bean. It's what lead me to the question above. – robert_difalco Mar 07 '14 at 00:46

1 Answers1

9

An example:

@Component
public class SomeComponent { }

The above will in practice create the same as:

public class SomeComponent { }
@Configuration
public class SomeComponentConfig {
    @Bean
    public SomeComponent someComponent() {
        return new SomeComponent();
    }
}

The advantage of @Component is clear: It is less code!

On the other hand, @Bean is powerful and has many use cases; for example if SomeComponent is in an existing library that you can't edit, or you simply don't want to clutter it with Spring or @Injectannotations.

holmis83
  • 15,922
  • 5
  • 82
  • 83
  • Another thing to keep in mind is that it is nice to keep stuff that requires specific configuration as a \@Bean. For example defining a redis host or database credentials. That allows you to change per-instance stuff in a configuration class. If it has no per-instance configuration you may as well just created a \@Component (or \@Named). – robert_difalco Mar 20 '14 at 18:04