springboot的configuration类无法注入bean

发布于 2022-09-03 12:47:07 字数 6360 浏览 10 评论 0

@Configuration
public class ScheduledTasks implements Job{

    @Autowired
    private GridFSService gridFSService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        this.gridFSService.saveFiles();
    }
}

我使用的注解配置,但是gridFSService总是会报空指针异常。请问在@Configuration配置类里面应该如何注入bean呢?
谢谢!

GridFSService如下:

@Component
public class GridFSService {

    @Autowired
    MongoOperations mongoOperations;

    @Autowired
    private BookRepository bookRepository;

    private static Logger logger = Logger.getLogger(GridFSService.class);

    public void saveFiles() {

        DB db = mongoOperations.getCollection(mongoOperations.getCollectionName(TextBook.class)).getDB();
        db.requestStart();
        List<File> files = new ArrayList<File>();
        files = FileUtil.listFiles(Constants.UN_SAVED_PATH_LOCAL, files);
        if(files.size() != 0){
            if(logger.isInfoEnabled()){
                logger.info(files.size() + " books ready to save.");
            }
            for(File scannedFile: files){
                String originalFileName = scannedFile.getName().substring(
                        scannedFile.getName().indexOf(Constants.UNDER_LINE)+1,
                        scannedFile.getName().length());
                GridFSInputFile gfsInput;
                try {
                    gfsInput = new GridFS(db, "fs").createFile(scannedFile);
                    gfsInput.setId(new ObjectId(new Date()));
                    // set gridFs chunckSize as 10M
                    gfsInput.setChunkSize(1024 * 1024 * 10L);
                    // set extension name
                    gfsInput.setContentType("txt");
                    // set file name saved in gridfs
                    gfsInput.setFilename(originalFileName);
                    gfsInput.save();
                    if(logger.isInfoEnabled()){
                        logger.info("save book [" + originalFileName + "] to gridFS");
                    }

                    TextBook book = new TextBook();
                    book.setId(gfsInput.getId().toString());
                    book.setTitle(originalFileName);
                    book.setAuthor(null);
                    book.setUploadDate(new Date().getTime());
                    book.setUploaderName(null);
                    book.setMailTimes(0L);
                    book.setKindleMailTimes(0L);
                    book.setDownloadTimes(0L);
                    book.setSize(gfsInput.getLength());
                    book.setFormat(gfsInput.getContentType());
                    bookRepository.save(book);
                    if(logger.isInfoEnabled()){
                        logger.info("save book [" + originalFileName + "] to collection");
                    }

                    // eg: /usr/local/src/files/unsaved/20160815/*
                    String unSavedFilePath = scannedFile.getPath();
                    if(unSavedFilePath.contains(Constants.SPACE)){
                        unSavedFilePath.replace(Constants.SPACE, Constants.BACKSLASH+Constants.SPACE);
                    }
                    File savedFile = new File(Constants.SAVED_PATH_LOCAL + DateFormatUtils.parseDateToString(new Date().getTime()));
                    if(!savedFile.exists()) {
                        if(logger.isInfoEnabled()){
                            logger.info("make dir: " + savedFile.getPath());
                        }
                        savedFile.mkdirs();
                    }
                    /*String command = "mv " + unSavedFilePath + " " + savedFile.getPath();
                    if(logger.isInfoEnabled()){
                        logger.info("prepared to execute command: " + command);
                    }
                    // execute linux command to move scanned file to the destination directory.
                    Process process = Runtime.getRuntime().exec(command);*/
                    FileUtil.moveFile(unSavedFilePath,savedFile.getPath());

                    if(logger.isInfoEnabled()){
                        logger.info("file [" + scannedFile.getName() + "] has been moved to the destination directory");
                    }
                } catch (IOException e) {
                    if(logger.isErrorEnabled()){
                        logger.error("save file to gridFS failed!", e);
                    }
                }
                db.requestDone();
            }
        } else {
            if(logger.isInfoEnabled()){
                logger.info("no files scanned!");
            }
        }
    }

    public File readFiles(String fileObjectId) {
        DB db = mongoOperations.getCollection(mongoOperations.getCollectionName(TextBook.class)).getDB();

        // query file saved in gridfs
        // by file name
        //GridFSDBFile gfsFile = new GridFS(db, "fs").findOne("application.properties");
        // by objectId
        GridFSDBFile gfsFile = new GridFS(db,"fs").findOne(new ObjectId(fileObjectId));
        try {
            File preparedAttachedFile = new File(gfsFile.getFilename());
           /* if (!preparedAttachedFile.exists()) {
                preparedAttachedFile.createNewFile();
            }*/
           // gfsFile.writeTo("src/main/resources/" + new Date().getTime() + "-" + uploadedFile.getName());
            gfsFile.writeTo(preparedAttachedFile);
            return preparedAttachedFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}

异常信息如下:

org.quartz.SchedulerException: Job threw an unhandled exception.
    at org.quartz.core.JobRunShell.run(JobRunShell.java:227) ~[quartz-1.8.5.jar:na]
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549) [quartz-1.8.5.jar:na]
Caused by: java.lang.NullPointerException: null
    at com.kindlepocket.cms.ScheduledTasks.execute(ScheduledTasks.java:25) ~[classes/:na]
    at org.quartz.core.JobRunShell.run(JobRunShell.java:216) ~[quartz-1.8.5.jar:na]
    ... 1 common frames omitted

启动类位于顶层目录:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

疑心病 2022-09-10 12:47:07

发现题主用的是quartz的job,关键在于quartz的job和普通的springboot的类不一样,不能这样注入。具体可参考这个讨论

解决方案的话,这个demo项目可以借鉴

北城挽邺 2022-09-10 12:47:07

包名不同,没有扫描到吧。顺便把异常贴出来。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文