这是我工作的当前代码。
方法一
@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
注释之间的区别。
最佳答案
它们是等价的。
当您拥有 NameClient 类并因此可以在其源代码中添加 Spring 注释时,您通常会使用第二个。
当您不拥有 NameClient 类时,您将使用第一个,因此无法使用适当的 Spring 注释对其进行注释。
关于Spring - 我应该使用@Bean 还是@Component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30539378/