I've been trying to use a springboot project that can integrate with mysql and jasperreports. The idea is that the user can add whoever to the database and then print a report with all entities. The error is at viewReport() function on my controller. It says that this.userService is null
@Controller
public class AppController {
@Autowired
private UserRepository repo;
private UserService userService;
@GetMapping("")
public String viewHomePage() {
return "index";
}
@GetMapping("/register")
public String showSignUpForm(Model model) {
model.addAttribute("user", new User());
return "signup_form";
}
@GetMapping("/report")
public String generateReport() {
userService.viewReport();
return "index";
}
@PostMapping("/process_register")
public String processRegistration(User user) {
repo.save(user);
return "register_success";
}
}
Here is my controller. The error being the userService.viewReport();
@Service
public class UserService {
@Autowired
private UserRepository repo;
public String viewReport() {
Log.info("Preparing the pdf report via Jasper.");
try {
createPdfReport(repo.findAll());
Log.info("File successfully saved at given path.");
} catch (final Exception e) {
Log.error("Some error has occured while preparing PDF document.");
e.printStackTrace();
}
return "Done in ViewReport";
}
public void createPdfReport(final List<User> users) throws JRException {
//Fetching .jrxml file from resources folder.
final InputStream stream = this.getClass().getResourceAsStream("/report.jrxml");
//compile report from .jrxml to .jasper
final JasperReport report = JasperCompileManager.compileReport(stream);
//Fetch users from the data source
final JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(users);
//Adding the additional parameters to the pdf
final Map<String, Object> parameters = new HashMap<>();
parameters.put("CreatedBy", "edu.sru.Smith" );
//filling report with data from database
final JasperPrint print = JasperFillManager.fillReport(report, parameters, source);
//place file in c:drive
final String filePath = "C://CPSC-488";
//export report to pdf file
JasperExportManager.exportReportToPdfFile(print, filePath "Employee_Report.pdf");
}
} ```
That is my service class that autofills with the data from the MySQL database. I have tried adding a number of annotations and other things, but I haven't had success with anything. I'm honestly just new to this whole springboot thing and annotations overall and I have no idea where to go from here.
CodePudding user response:
@Autowired annotation should be placed on each field that needs injection.
@Autowired
private UserRepository repo;
@Autowired
private UserService userService;