我有一个创建Retrofit“beans”的配置类(见下文),然后(应该)将这些bean注入到服务中。但是,此时似乎在提供 bean名称的服务之前没有创建Retrofit bean“exampleRepository”,即“@Bean(name = exampleRepository)”。我已经多次使用过这个设置而没有问题,但它在这里失败了。有谁知道为什么?代码如下。
配置
@Configuration
@ConfigurationProperties("example")
public class RetrofitConfig {
@NotNull
private String baseUrl;
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
@Bean(name = "retrofitBuilder")
public Retrofit.Builder retrofitBuilder() {
return new Retrofit.Builder().addConverterFactory(JacksonConverterFactory.create());
}
@Bean(name = "okHttpClient")
public OkHttpClient okHttpClient() {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(httpLoggingInterceptor);
return httpClient.build();
}
@Bean(name = "exampleRetrofit")
public Retrofit exampleRetrofit(@Qualifier("retrofitBuilder") Retrofit.Builder builder, @Qualifier("okHttpClient") OkHttpClient okHttpClient) {
return builder.client(okHttpClient).baseUrl(getBaseUrl()).build();
}
@Bean(name = "exampleRepository")
public ExampleContract exampleRespository(@Qualifier("exampleRetrofit") Retrofit retrofit) {
return retrofit.create(ExampleContract.class);
}
}
服务
@Service
@Transactional
public class ExampleService {
private ExampleContract exampleRepository;
public ExampleService(ExampleContract exampleRepository) {
this.exampleRepository = exampleRepository;
}
}
答案 0 :(得分:0)
您的bean声明中有一个拼写错误'exampleRe s pository'。
默认情况下,spring按类型注入bean,在服务声明中为存储库声明添加@Qualifier或更正拼写错误。
下面是关于基于名称的注射工作的好文章 https://www.logicbig.com/tutorials/spring-framework/spring-core/inject-bean-by-name.html