Springboot 工具类中引用service/Component

描述:工具类中有时需要使用配置文件中的变量,或调用service中的方法,这时需要注入service或component

  • 静态类中是无法直接引入service的,会报空指针异常
  • 可通过spring注解注入,如下:

方式一:

package com.apigateway.util;

import com.apigateway.config.GlobalConfig;
import com.apigateway.config.ThreadPoolConfig;
import com.apigateway.dto.LogCollectorDto;
import com.apigateway.dto.ParamDto;
import com.apigateway.enums.LogLevelEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import static com.apigateway.constant.CacheConstant.MQSWITCH_OPEN;

/**
 * @Author:xingpf
 * @Date: 2020/5/6  16:06
 * @Descriptions: 日志工具类,将日志打到MQ或日志采集平台
 */
@Component
public class LogUtil {

    private static final Logger log = LoggerFactory.getLogger(LogUtil.class);

    @Resource
    private GlobalConfig config;

    @Resource
    private ThreadPoolConfig threadConfig;


    private static GlobalConfig globalConfig;

    private static ThreadPoolConfig threadPoolConfig;


    @PostConstruct
    public void init() {
        globalConfig = this.config;
        threadPoolConfig = this.threadConfig;
    }

    /**
     * 将报文推至MQ
     *
     * @param paramDto
     */
    public static void logToMq(ParamDto paramDto) {
        //信息推送至MQ的开关开启时,才将信息推送至MQ,开关在nacos配置
        if (MQSWITCH_OPEN.equals(globalConfig.getLogToMqSwitch())) {
            threadPoolConfig.execute(() -> {
                try {
                    UdpUtil.sendMsgToMQ(paramDto.toJsonString(), globalConfig.getMqHostAddress(),
                            globalConfig.getMqHostPort(), globalConfig.getMqHostTimeOut());
                } catch (Exception e) {
                    log.error("[TranspondServiceImpl] [logToMq] Exception=", e);
                    wrapLogCollectorDto(paramDto.getSeqNum(),
                            "信息推送至MQ异常,消息内容={" + paramDto.toJsonString() + "}, Exception=" + e,
                            LogLevelEnum.EVENT.getLevel());
                }
            });
        }
    }

方式二:

package com.apigateway.util;

import com.apigateway.config.GlobalConfig;
import com.apigateway.config.ThreadPoolConfig;
import com.apigateway.dto.LogCollectorDto;
import com.apigateway.dto.ParamDto;
import com.apigateway.enums.LogLevelEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import static com.apigateway.constant.CacheConstant.MQSWITCH_OPEN;

/**
 * @Author:xingpf
 * @Date: 2020/5/6  16:06
 * @Descriptions: 日志工具类,将日志打到MQ或日志采集平台
 */
@Component
public class LogUtil {

    private static final Logger log = LoggerFactory.getLogger(LogUtil.class);

    private static GlobalConfig globalConfig;

    private static ThreadPoolConfig threadPoolConfig;
 
    @Autowired
    public void setGlobalConfig(GlobalConfig globalConfig) {
        LogUtil.globalConfig = globalConfig;
    }

    @Autowired
    public void setThreadPoolConfig(ThreadPoolConfig threadPoolConfig) {
        LogUtil.threadPoolConfig = threadPoolConfig;
    }


    /**
     * 将报文推至MQ
     *
     * @param paramDto
     */
    public static void logToMq(ParamDto paramDto) {
        //信息推送至MQ的开关开启时,才将信息推送至MQ,开关在nacos配置
        if (MQSWITCH_OPEN.equals(globalConfig.getLogToMqSwitch())) {
            threadPoolConfig.execute(() -> {
                try {
                    UdpUtil.sendMsgToMQ(paramDto.toJsonString(), globalConfig.getMqHostAddress(),
                            globalConfig.getMqHostPort(), globalConfig.getMqHostTimeOut());
                } catch (Exception e) {
                    log.error("[TranspondServiceImpl] [logToMq] Exception=", e);
                    wrapLogCollectorDto(paramDto.getSeqNum(),
                            "信息推送至MQ异常,消息内容={" + paramDto.toJsonString() + "}, Exception=" + e,
                            LogLevelEnum.EVENT.getLevel());
                }
            });
        }
    }  
}

注意:如果不是全包扫描的话,在启动类上的@ComponentScan注解中记得扫描工具类所在的包

ps:文章用于记录问题,如有不当之处,欢迎批评指正!

你可能感兴趣的:(Springboot)