Decided to venture into Spring Boot and have hit a big snag with @Autowired property returning null. There are many solutions here I've tried but none has worked on my particular case.
To state, the common theme, @Autowired in my Application.java works fine but not in my Controller. (@Autowired works here)
@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
}
}
Here are my steps: 1. In WebAppConfig.java, I registered a secondary 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/*");
}
Also in WebAppConfig.java, I registered a 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>();
}
}
In this new Controller, I @Autowired a parser variable - NULL occurs in here
@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);
}
}
}
What did I miss in my setup/configuration? Any help would be highly appreciated.