SpringBoot中添加监听器及创建线程

Application主程序上添加注解
@ServletComponentScan(basePackages= {"com.qyj.listeners"})// 添加监听器所在的包名

监听程序


package com.qyj.listeners;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AudioPlayListener implements ServletContextListener {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${qyj.fee-type}")
    private String feeType;

    // 当后台被初始化,即发生了tomcat启动了事件,固定用法
    @Override
    public void contextInitialized(ServletContextEvent event) {
        // 你要做的事儿,写在这里
        System.out.println("AudioPlay is running(语音播报-循环监听中)...");
        // 新建线程while循环处理语音播报
        new Thread(new AudioPlayThread(redisTemplate, feeType)).start();
    }

    // 当后台被销毁,即发生了tomcat关闭了事件,固定用法
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("后台被销毁");
    }
}

新建线程

package com.qyj.listeners;

import com.qyj.constant.RedisConstant;
import com.qyj.utils.AudioPlayUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class AudioPlayThread implements Runnable{
    // 因为线程是new出来的 所以此处不能再通过依赖注入获取信息了
    private String feeType;
    private StringRedisTemplate redisTemplate;

    public AudioPlayThread(StringRedisTemplate redisTemplate, String feeType) {
        this.redisTemplate = redisTemplate;
        this.feeType = feeType;
    }

    @Override
    public void run() {
        while(true){
            try {
                System.out.println("这是继承Thread类创建的线程");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值