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:文章用于记录问题,如有不当之处,欢迎批评指正!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: Spring Boot是一个轻量级的框架,它可以让你快速地构建出一个单独的,可执行的jar包,这样你就可以通过使用`java -jar`命令来运行应用。 为了使用Spring Boot的工具类模块,你需要在你的应用引入它们的依赖。这可以通过在你的`pom.xml`文件添加对应的依赖来实现。 例如,如果你想使用Spring Boot的Web模块,你可以在你的`pom.xml`文件添加如下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 然后,你就可以在你的应用使用Spring Boot的Web模块了。 要运行应用,你可以使用以下命令: ``` java -jar myapp.jar ``` 其`myapp.jar`是你的应用打包后生成的jar文件。 希望这对你有帮助! ### 回答2: 要启动springboot工具类模块,首先需要在项目的pom.xml文件引入spring-boot-starter-parent依赖。接着,创建一个带有main方法的启动类,使用@SpringBootApplication注解标记该类为springboot应用的入口。 在启动类,可以使用@Autowired或@Resource注解来注入需要使用的工具类实例对象。确保工具类已被正确定义并且@Component或@Service注解标记,以便能够被自动扫描并生成实例。 接下来,在main方法使用SpringApplication类的run方法来启动应用程序。可以传入启动类的.class参数和命令行参数args。 最后,运行main方法,springboot工具类模块将会被启动并完成初始化。可以在控制台或日志观察到springboot的启动日志信息。 需要注意的是,在启动前,确认项目的配置文件(application.properties或application.yml)的配置项已正确设置,并且工具类所需的依赖已经在pom.xml文件声明和导入。这样才能确保工具类模块能够被正确加载和启动。 综上所述,启动springboot工具类模块的步骤是:添加依赖、创建启动类、注入工具类实例、运行main方法。 ### 回答3: 在SpringBoot,如果你的工具类模块是一个独立的项目,你可以按照以下步骤来启动它: 1. 首先,确保你的工具类模块包含了一个主启动类。这个类需要被注解`@SpringBootApplication`修饰,这样SpringBoot才能正确地扫描和初始化你的应用。 2. 使用构建工具(如Maven或Gradle)将工具类模块打包成可执行的jar文件。这可以通过运行构建命令(例如`mvn package`)来完成。 3. 在命令行,使用`java -jar`命令执行已打包的jar文件。命令的格式为`java -jar <jar文件名>.jar`。这将启动一个嵌入式的Tomcat服务器,并使用默认的服务器端口(通常为8080)。 4. 一旦jar文件成功启动,你可以通过访问`localhost:8080`来测试你的工具类模块。通常,SpringBoot会自动创建一个名为"health"的端点,可以通过访问`localhost:8080/actuator/health`来检查应用程序的运行状况。 总之,在使用SpringBoot工具类模块时,只需确保添加`@SpringBootApplication`注解的主启动类,并使用`java -jar`命令来执行打包好的jar文件即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值