Spring Boot @Autowired属性null

时间:2017-12-23 16:33:11

标签: java spring servlets spring-boot autowired

决定冒险进入Spring Boot并且在@Autowired属性返回null时遇到了大麻烦。我已经尝试了许多解决方案,但没有一个解决我的具体案例。

要说明,我的Application.java中的常见主题@Autowired工作正常但不在我的Controller中。 (@Autowired在这里工作)

@SpringBootApplication
public class JackandjasonApplication implements ApplicationRunner{

private final Logger logger = 
LoggerFactory.getLogger(JackandjasonApplication.class);

@Autowired
JackAndJasonPDFParser parser;

@Value("${remote.schedule.file}")
private String file;

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

@Override
public void run(ApplicationArguments args) throws Exception {
    logger.info("Processing Schedule file: " + file);
    parser.parse(file);  // <--- This works fine
}

}

以下是我的步骤: 1.在WebAppConfig.java中,我注册了一个辅助servlet:

@Bean
public ServletRegistrationBean<com.jackandjason.route.planner.jackandjason.servlet.JackandjasonFileUploadServlet> getScheduleServlet() {
    return new ServletRegistrationBean<>(new com.jackandjason.route.planner.jackandjason.servlet.JackandjasonFileUploadServlet(), "/schedule/upload/file/*");
}

同样在WebAppConfig.java中,我注册了一个Bean:

@Bean
@Primary
public JackAndJasonPDFParser getParser() {
    return new JackAndJasonPDFParser();
}

JackAndJasonPDFParser.java

    @ComponentScan(basePackages={"com.jackandjason.route.planner.jackandjason"})
    @Service
    public class JackAndJasonPDFParser {

    @Autowired(required = true)
    private ScheduleRepository schedRepo;

    private static Logger logger = LoggerFactory.getLogger(JackAndJasonPDFParser.class);
    Gson gson = new Gson();
    private List<Schedule> schedules;
    public List<Schedule> parse(String path) {
        List<Schedule> listOfSchedules = new ArrayList<Schedule>();
    }
}

在这个新的Controller中,我@Autowired一个解析器变量 - NULL出现在这里

   @Controller
   public class JackandjasonFileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private final Logger logger =  
    LoggerFactory.getLogger(JackandjasonFileUploadServlet.class);

    @Autowired
    private JackAndJasonPDFParser parser;

    private static final int MAX_MEMORY_SIZE = (1024 * 1024 * 2);
    private static final int MAX_REQUEST_SIZE = (1024 * 1024);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if(!isMultipart) {
            return;
        }

        //Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Set the size threshold for writing file directly to the server disk.
        factory.setSizeThreshold(MAX_MEMORY_SIZE);

        //Set the directory used to temporarily store files larger than the threshold. I use the Java temp directory
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        String dailySchedDir = getServletContext().getRealPath("") + "daily_schedule";

        //Create a file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        //Set the overall request size limit
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            //Parse the request
            List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
            logger.info("List of Items: " + gson.toJson(items));
            Iterator<FileItem> itr = items.iterator();
            String filePath = new String();
            while(itr.hasNext()) {
                FileItem item = itr.next();
                if(!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    filePath = dailySchedDir + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                    logger.info("Uploading " + filePath);
                    item.write(uploadedFile);
                }
            }
            //Parse the file
            List<Schedule> listOfSchedules = parser.parse(filePath);    // <---- NULL 
            if(listOfSchedules != null) {
                logger.info(filePath + " successfully parsed");
            } else {
                logger.error("An error occurred while parsing " + filePath);
            }
        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

    }
}

我在设置/配置中错过了什么?任何帮助都将受到高度赞赏。

0 个答案:

没有答案