线程任务类bean注入的问题(不容易注入bean的问题通解)
有些类不是标准的service类,注入bean会有问题
加上compoent注解依然不行,
比如对于线程任务类,注入一些service时候有时候会报bean不能创建
这个思路我觉着还是比较通用的,分享一下
有些类不是标准的service类,注入bean会有问题
加上compoent注解依然不行,
比如对于线程任务类,注入一些service时候有时候会报bean不能创建
比如刚才我使用的封装的一个memcache的一个class 如下图会报错
这个思路我觉着还是比较通用的,分享一下
如下
InvoiceAuthorizationTask.java
private CPCacheClient cPCacheClient ;
private TokenGetRequest tokenGetDTO;
@Value("${baiwang.authorizationApi.url}")
private String authorizationApiUrl;
public InvoiceAuthorizationTask(TokenGetRequest tokenGetDTO,
String authorizationApiUrl,CPCacheClient cPCacheClient) {
this.tokenGetDTO = tokenGetDTO;
this.authorizationApiUrl = authorizationApiUrl;
this.cPCacheClient= cPCacheClient ;
}
对于这个类的使用 (我在使用task类的内部注入 然后传进去)
public class SellerInfoServiceImpl implements SellerInfoService {
@Autowired
private CPCacheClient cPCacheClient ;
private void recursionGetToken(TokenGetRequest tokenGetDTO,
List<LoginResponseEntity> resList,Integer retryTimes) {
LoginResponseEntity res = new LoginResponseEntity();
ExecutorService es = ExecutorServiceBillingTask.getEs();
Future<LoginResponseEntity> resFuture = es.submit(new InvoiceAuthorizationTask(tokenGetDTO,
authorizationApiUrl,cPCacheClient));
try {
Random random = new Random();
if( random.nextInt(10)>2) {
throw new TimeoutException();
}
//TODO 时间要调整下
res = resFuture.get(Integer.parseInt(overtime),TimeUnit.SECONDS);
}
catch (TimeoutException |InterruptedException | ExecutionException e) {
//只处理超时
InvoicePurchaseQueryResponse c = new InvoicePurchaseQueryResponse();
res.setCode(ResponseCodeEnum.BUSINESS_TIME_OUT.getCode());
res.setMessage( ResponseCodeEnum.BUSINESS_TIME_OUT.getMessage());
}