autowire - springboot的configuration类无法注入bean

查看:2522
本文介绍了autowire - springboot的configuration类无法注入bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

@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);
    }

}

解决方案

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

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

这篇关于autowire - springboot的configuration类无法注入bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆