bra*_*orm 3 spring dependency-injection spring-mvc autowired
这是我工作中的当前代码.
方法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);
}
}
Run Code Online (Sandbox Code Playgroud)
这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
}
Run Code Online (Sandbox Code Playgroud)
@Bean我没有使用配置,而是想要遵循这种模式:
方法2
@Configuration
public class AppConfig {
@Bean
@Autowired(required = false)
public HttpClient createHttpClient() {
// do some connections configuration
return new HttpClient();
}
}
Run Code Online (Sandbox Code Playgroud)
并使用自动扫描功能来获取bean
@Service //@Component will work too
public class NameClient {
@Autowired
private HttpClient client;
@Value("${ServiceUrl:NotConfigured}")
private String url;
public NameClient() {}
// other methods
}
Run Code Online (Sandbox Code Playgroud)
为什么使用上面的第一种方法/首选?一个优于另一个的优势是什么?我读到了使用@Component和@Bean注释之间的区别.
他们是等同的.
当您拥有NameClient类时,通常会使用第二个,因此可以在其源代码中添加Spring注释.
当您不拥有NameClient类时,您将使用第一个,因此无法使用相应的Spring注释对其进行注释.
| 归档时间: |
|
| 查看次数: |
158 次 |
| 最近记录: |