spring boot 定时任务Scheduler 报错 Cause: java.lang.IllegalStateException: No thread-bound request found

刚做开发,
最近用springboot 自带的Scheduler作一个定时任务 ,用foreach 遍历list元素判断满足条件就向数据库插入一条数据。不插入的话就不报错,但是@authorized注入一个Dao,insert 就报错。
springbboot+mybatisplus

请问是什么原因,如何解决。

img

img

img



@Component
public class Scheduler {
    @Autowired
    private EventConfigService eventConfigService;
    @Autowired
    private MessageRemindService messageRemindService;

    @Scheduled(cron = "*/20 * * * * ?") 
    @Scheduled
    @Transactional
    public void scheduler() {
        System.out.println("================================================执行 scheduler1:根据第一次消息提醒");
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        System.out.println(formatter.format(calendar.getTime()));
        String date = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        System.out.println(date);

        HashMap eventConfigViewData = eventConfigService.getEventConfigViewData(Collections.singletonList("2021-09-16,2021-09-16"), null);
        List<mmc_event_config_repeat> list = (List<mmc_event_config_repeat>) eventConfigViewData.get("2021-09-16");
        list.stream().forEach(item -> {
            message_remind message_remind = new message_remind();
            //获取重复配置jsonb中的日期
            JSONObject jsonObject = JSONObject.parseObject(item.getEvent_config_repeat());
            String value = jsonObject.get("data").toString();
            JSONArray jsonArray = JSONArray.parseArray(value);
            //日程重复类型
            String repeatType = item.getEvent_repeat_type();

            if (item.getEventEntity() != null) {
                //根据第一次提醒时间
                long RemindMinutes = (item.getEventEntity().getStart_time().getTime() - item.getEventEntity().getFirst_remind().getTime()) / (1000 * 60);
                //计算提前多少分钟提醒
                calendar.add(Calendar.MINUTE, (int) RemindMinutes);
                //计算出当前时间加上提醒分钟后的时间;日期和时间
                String eventRemindDate = formatter.format(calendar.getTime());
                //获取日程开始时间的 时、分
                String startTime = new SimpleDateFormat("HH:mm").format(item.getEventEntity().getStart_time());
                String endTime = new SimpleDateFormat("HH:mm").format(item.getEventEntity().getEnd_time());
                boolean check = checkEventConfigService(jsonArray, calendar, repeatType, startTime);
                if (check) {
                    System.out.println("1:开始");
                    String calculateData = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
                    //日历组件根据日期获取星期几
                    SimpleDateFormat weekDateFormat = new SimpleDateFormat("EEEE");
                    String week = null;
                    week = weekDateFormat.format(calendar.getTime());

                    message_remind.setMessage_is_read("0");
                    message_remind.setMessage_is_readname("否");
                    message_remind.setMessage_object_type("system");
                    message_remind.setName("您有一条消息请查收");
                    messageRemindService.save(message_remind);
                    System.out.println("1:结束");
                }
            }
        });
    }

2021-09-26 16:06:21 DEBUG taskScheduler-1 cn.com.recloud.one.platform.data.handler.UpdateRelatedFieldMetaHandler start insert fill.....
Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2cc1628e]
Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2cc1628e]
Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2cc1628e]
2021-09-26 16:06:21 ERROR taskScheduler-1 org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler Unexpected error occurred in scheduled task
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
### The error may exist in cn/com/recloud/byh/messageremind/dao/MessageRemindDao.java (best guess)
### The error may involve cn.com.recloud.byh.messageremind.dao.MessageRemindDao.insert
### The error occurred while executing an update
### Cause: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:92)
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:440)
    at com.sun.proxy.$Proxy101.insert(Unknown Source)
    at org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:271)
    at com.baomidou.mybatisplus.core.override.MybatisMapperMethod.execute(MybatisMapperMethod.java:60)
    at com.baomidou.mybatisplus.core.override.MybatisMapperProxy.invoke(MybatisMapperProxy.java:96)
    at com.sun.proxy.$Proxy144.insert(Unknown Source)
    at com.baomidou.mybatisplus.extension.service.IService.save(IService.java:59)
    at cn.com.recloud.one.platform.base.service.CoreBaseServiceImpl.save(CoreBaseServiceImpl.java:93)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205)
    at com.sun.proxy.$Proxy145.save(Unknown Source)
    at cn.com.recloud.byh.scheduler.Scheduler.lambda$scheduler$0(Scheduler.java:93)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
    at cn.com.recloud.byh.scheduler.Scheduler.scheduler(Scheduler.java:40)
    at cn.com.recloud.byh.scheduler.Scheduler$$FastClassBySpringCGLIB$$924b522f.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
    at cn.com.recloud.byh.scheduler.Scheduler$$EnhancerBySpringCGLIB$$60ee2fcf.scheduler(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
### The error may exist in cn/com/recloud/byh/messageremind/dao/MessageRemindDao.java (best guess)
### The error may involve cn.com.recloud.byh.messageremind.dao.MessageRemindDao.insert
### The error occurred while executing an update
### Cause: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:199)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:184)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:426)
    ... 43 common frames omitted
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
    at org.springframework.web.context.support.WebApplicationContextUtils.currentRequestAttributes(WebApplicationContextUtils.java:313)
    at org.springframework.web.context.support.WebApplicationContextUtils.access$400(WebApplicationContextUtils.java:66)
    at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:329)
    at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:324)
    at org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler.invoke(AutowireUtils.java:294)
    at com.sun.proxy.$Proxy86.getUserPrincipal(Unknown Source)
    at cn.com.recloud.one.platform.user.LocalUserUtil.getPrincipal(LocalUserUtil.java:141)
    at cn.com.recloud.one.platform.user.LocalUserUtil.getCurrentUser(LocalUserUtil.java:184)
    at cn.com.recloud.one.platform.user.LocalUserUtil.getUserId(LocalUserUtil.java:106)
    at cn.com.recloud.one.platform.data.handler.UpdateRelatedFieldMetaHandler.insertFieldFill(UpdateRelatedFieldMetaHandler.java:38)
    at cn.com.recloud.one.spring.handler.FieldMetaHandler.insertFill(FieldMetaHandler.java:31)
    at com.baomidou.mybatisplus.core.MybatisDefaultParameterHandler.lambda$insertFill$1(MybatisDefaultParameterHandler.java:179)
    at java.base/java.util.Optional.ifPresent(Optional.java:183)
    at com.baomidou.mybatisplus.core.MybatisDefaultParameterHandler.insertFill(MybatisDefaultParameterHandler.java:176)
    at com.baomidou.mybatisplus.core.MybatisDefaultParameterHandler.process(MybatisDefaultParameterHandler.java:111)
    at com.baomidou.mybatisplus.core.MybatisDefaultParameterHandler.processParameter(MybatisDefaultParameterHandler.java:84)
    at com.baomidou.mybatisplus.core.MybatisDefaultParameterHandler.<init>(MybatisDefaultParameterHandler.java:55)
    at com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver.createParameterHandler(MybatisXMLLanguageDriver.java:34)
    at com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver.createParameterHandler(MybatisXMLLanguageDriver.java:28)
    at org.apache.ibatis.session.Configuration.newParameterHandler(Configuration.java:579)
    at org.apache.ibatis.executor.statement.BaseStatementHandler.<init>(BaseStatementHandler.java:69)
    at org.apache.ibatis.executor.statement.PreparedStatementHandler.<init>(PreparedStatementHandler.java:41)
    at org.apache.ibatis.executor.statement.RoutingStatementHandler.<init>(RoutingStatementHandler.java:46)
    at org.apache.ibatis.session.Configuration.newStatementHandler(Configuration.java:592)
    at com.baomidou.mybatisplus.core.executor.MybatisSimpleExecutor.doUpdate(MybatisSimpleExecutor.java:52)
    at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
    at com.baomidou.mybatisplus.core.executor.MybatisCachingExecutor.update(MybatisCachingExecutor.java:83)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.apache.ibatis.plugin.Invocation.proceed(Invocation.java:49)
    at com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor.intercept(OptimisticLockerInterceptor.java:69)
    at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)
    at com.sun.proxy.$Proxy251.update(Unknown Source)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:197)
    ... 49 common frames omitted

有没有具体的解决办法

代码不全,错误不全。如果你用的是mybatisp的话,可以直接用它的api this.save(保存对象)去做保存,没必要自己去写

把报错地方的代码整个贴出来,这谁能看出来,mybatisplus不用自己写数据库操作的,框架自带数据库CRUD操作