springboot2.* 普通utils类调用service接口/mapper接口,解决方案

问题描述:

在springboot 开发中,需要在utils和多线程中使用mapper/Service接口,将数据写入mysql数据库。 普通工具类中自动注入失败。

网上给的方案使用@Component注解,多次尝试后失败,于是使用了别的方案。 详情下方两段代码

 

解决方案: 新建BeanContext 类实现springframework的ApplicationContextAware类

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Author: louis
 * @Date: 2019/4/17 下午1:51
 */

@Component
public class BeanContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanContext.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T)applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clz) throws BeansException {
        return (T)applicationContext.getBean(clz);
    }
}

在普通类中使用方法:

/**
 * @Author: louis
 * @Date: 2019/6/24 下午7:12
 *代码段取自一个调度job 使用spring cron调度es统计数据写入mysql
  *调用mapper接口  注入
*private CoreService coreService;
*this.coreService=BeanContext.getApplicationContext().getBean(CoreService.class);
 */
public class EsFlowCountByIpJob {

    //第一步:注入CoreService接口
    private CoreService coreService;

    //第二步:在方法中getBean

    public void esFlowCount(){
    
   this.coreService=BeanContext.getApplicationContext().getBean(CoreService.class);

    //第三步:实现业务逻辑,这里我调用了coreService的updateFlowCount方法,更新数据库数据
   coreService.updateFlowCount(to_client,to_server,update_time);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

测试可以正常调用,解决问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值