brain storm
brain storm

Reputation: 31252

Spring - should I use @Bean or @Component?

Here is the current code at my work.

Method 1

@Configuration
public class AppConfig {

    @Bean
    @Autowired(required = false)
    public HttpClient createHttpClient() {
        // do some connections configuration
        return new HttpClient();
    }

    @Bean
    @Autowired
    public NameClient nameClient(HttpClient httpClient,
                                 @Value("${ServiceUrl:NotConfigured}") 
                                 String serviceUrl) {
        return new NameClient(httpClient, serviceUrl);
    }

}

And the NameClient is a simple POJO looks like following

public class NameClient {
    private HttpClient client;
    private String url;

    public NameClient(HttpClient client, String url) {
        this.client = client;
        this.url = url;
    }

    // other methods 
}

Instead of using @Bean to configure, I wanted to follow this pattern:

Method 2

@Configuration
public class AppConfig {

  @Bean
  @Autowired(required = false)
  public HttpClient createHttpClient() {
    // do some connections configuration
    return new HttpClient();
  }
}

And use auto-scanning feature to get the bean

@Service //@Component will work too
public class NameClient {

    @Autowired
    private HttpClient client;

    @Value("${ServiceUrl:NotConfigured}")
    private String url;

    public NameClient() {}

    // other methods 
}

Why the first method above is used/preferred? What is the advantage of one over the other? I read about the difference between using @Component and @Bean annotations.

Upvotes: 3

Views: 231

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

They're equivalent.

You would typically use the second one when you own the NameClient class and can thus add Spring annotations in its source code.

You would use the first one when you don't own the NameClient class, and thus can't annotate it with the appropriate Spring annotations.

Upvotes: 8

Related Questions