如何在控制器操作中实例化CommandLineRunner以及所有@Autowired属性?

时间:2019-04-23 02:19:16

标签: java spring spring-boot

我有

@Component
public class WeeklyReport implements CommandLineRunner {
    @Autowired
    private RecipientMapper recipientMapper;

    @Override
    public void run(String... args) throws Exception {
        String[] recipients = recipientMapper.all();

@Controller
public class MyController extends BaseController implements ErrorController {
    @RequestMapping(value="/admin/weekly-report-run", method=RequestMethod.POST)
    public ModelAndView weeklyReportRun(WeeklyReport weeklyReport) {
        try {
            weeklyReport.run();

但是我在receiveMapper.all()处收到NullPointerException。我如何实例化CommandLineRunner,以便所有@Autowired字段都自动连接,并且可以通过从命令行以及从控制器调用代码来重用代码?我以为,通过将其指定为控制器方法的参数,Spring Boot可以实例化正确的对象以及所有子字段。

Spring Boot 1.5.19。

1 个答案:

答案 0 :(得分:0)

我添加了

@Autowired
private WeeklyReport weeklyReport;

对于控制器,并将其从控制器方法参数中删除,并且可以正常工作。该action方法能够看到自动连接的类变量。