非service类注入bean的一个通解(针对不容易注入bean的时候)

本文探讨了解决线程任务类中难以注入Bean的问题。通过构造方法传递依赖而非使用@Autowired注解,确保了线程任务能够正确获取所需的Service实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 线程任务类bean注入的问题(不容易注入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());
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值