我在spring boot中的计划作业正在给出异常并返回null

我在spring boot中的计划作业正在给出异常并返回null,spring,spring-boot,Spring,Spring Boot,我已经编写了调度作业的代码,即每5秒向数据库添加一次数据。虽然代码的结构正确,但我遇到了一些异常。每5秒调度一次作业,但数据库上什么也没有发生 package com.example.schedule.service; import com.example.schedule.dao.UserDao; import com.example.schedule.model.User; import org.springframework.scheduling.annotation.Scheduled;

我已经编写了调度作业的代码,即每5秒向数据库添加一次数据。虽然代码的结构正确,但我遇到了一些异常。每5秒调度一次作业,但数据库上什么也没有发生

package com.example.schedule.service;
import com.example.schedule.dao.UserDao;
import com.example.schedule.model.User;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class UserService {
    private UserDao userdao;
    @Scheduled(fixedRate = 5000)
    public void add2DBjob(){
       User user=new User();
        user.setName("xadmin "+ new Random().nextInt(3774480));
        userdao.save(user);
        System.out.println("added object in database at : "+new Date().toString());
    }

}
我有一个
User
实体,它还有两个属性name和id,其中id是主键

package com.example.schedule.model;
import lombok.*;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
    @Id
    @GeneratedValue
    private int id;
    private String name;


}
我有
application.properties
文件,我在下面附上了该文件的代码

server.port=9090
spring.datasource.url=jdbc:mysql://localhost:3306/job
spring.datasource.username=root
spring.datasource.password=Ph@ne#121
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
我有一个dao实例,它扩展了jpa存储库

package com.example.schedule.dao;

import com.example.schedule.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDao extends JpaRepository<User,Integer> {
}

请帮助我查找可能出现的错误?

您尚未初始化UserService类中的userdao对象,这导致了问题。你需要自动连线它

@Autowired
private UserDao userdao;


此外,请检查是否已在配置类中启用计划。如果没有,请在配置类中添加
@EnableScheduling
注释。您还可以通过XML配置启用调度。

您尚未初始化UserService类中的userdao对象,这会导致问题。你需要自动连线它

@Autowired
private UserDao userdao;


此外,请检查是否已在配置类中启用计划。如果没有,请在配置类中添加
@EnableScheduling
注释。您还可以通过XML配置启用调度。

@Autowired
添加到
UserService
中的
UserDao
字段,甚至更好。将其设置为最终版,并添加一个构造函数,该构造函数接受并分配
UserDao
。将
@Autowired
添加到
UserService
中的
UserDao
字段,甚至更好。将其设为final,并添加一个构造函数,该构造函数接受并分配
UserDao。