我在通过@Autowired进行接口的spring注入实现时遇到麻烦。
在我的代码中,我有一个用@Component注释的bean。我有一个通过@Autowired注释使用此bean的类。
但是Spring容器没有注入bean
按照代码说明我的情况
Bean
@Component
public class ExternalApiIntegrationImpl implements ExternalApiIntegration<User>{
private FactoryHeaders factoryHeaders;
private RestTemplate restTemplate;
final private static String URL_API_EXTERNAL = "https://reqres.in/api/users";
@Autowired
public void setFactoryHeaders(FactoryHeaders factoryHeaders) {
this.factoryHeaders = factoryHeaders;
}
@Autowired
public void setRestTemplate(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
@Override
public ResponseEntity<User> sendObjectForApi(User object) {
var headers = factoryHeaders.createHeaderWithoutAuth();
var request = new HttpEntity<>(object, headers);
final var response = restTemplate.exchange(URL_API_EXTERNAL, HttpMethod.POST, request, User.class);
return response;
}
}
普通消费者Bean
public class CustomWriter implements ItemWriter<User>{
private final DataSource dataSource;
@Autowired
private ExternalApiIntegration externalApiIntegration; //Set with null
private static final String QUERY_UPDATE_USERS =
"UPDATE " +
"users " +
"SET " +
"createdAt = ? " +
"WHERE " +
"user_id = ?";
public CustomWriter(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void write(List<? extends User> items) throws Exception {
items.forEach(i -> {
var response = this.externalApiIntegration.sendObjectForApi(i);
});
}
}
运行课程
@ComponentScan("com.br.savit0h.batchservicedemo")
@EnableAutoConfiguration
@SpringBootApplication
public class BatchServiceDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BatchServiceDemoApplication.class, args);
}
}
伙计们,谢谢您的关注。