【问题标题】:Spring - should I use @Bean or @Component?Spring - 我应该使用@Bean 还是@Component?
【发布时间】:2015-08-12 21:33:56
【问题描述】:

这是我工作的当前代码。

方法一

@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);
    }

}

NameClient 是一个简单的 POJO,如下所示

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

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

    // other methods 
}

我不想使用@Bean 进行配置,而是想遵循这种模式:

方法二

@Configuration
public class AppConfig {

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

并使用自动扫描功能获取 bean

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

    @Autowired
    private HttpClient client;

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

    public NameClient() {}

    // other methods 
}

为什么使用/首选上述第一种方法?一个比另一个有什么优势?我了解了使用 @Component@Bean 注释之间的区别。

【问题讨论】:

    标签: spring spring-mvc dependency-injection autowired


    【解决方案1】:

    它们是等价的。

    当您拥有 NameClient 类时,通常会使用第二个,因此可以在其源代码中添加 Spring 注释。

    当您不拥有 NameClient 类时,您将使用第一个,因此无法使用适当的 Spring 注释对其进行注释。

    【讨论】:

    • 这是一个有效的观点。尽管我们拥有代码,但我不确定为什么我们使用方法 1
    • 另一个原因可能是,如果您不想添加 Spring 特定的注释,因为此代码用于其他非 Spring 项目。
    猜你喜欢
    • 1970-01-01
    • 2018-04-03
    • 2010-09-09
    • 1970-01-01
    • 2016-10-31
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多