从SpringBoot中的CommandLineRunner访问数据

时间:2018-01-23 00:11:12

标签: java spring spring-boot command-line controller

在我的命令Line runner

@Controller
public class HelloController implements CommandLineRunner {

    static List<todos> todos;
  @Override
    public void run(String... args) throws Exception {
//todos.add(...)
   }

在第二个控制器类中:

@RequestMapping(value = "/list-todos", method = RequestMethod.GET)
public String showTodos(ModelMap model) throws IOException {
// I would access to the list of TODOs defined in HelloController 
    return "list-todos";
}

我的问题是如何从showTodos(在TODOController.java中)访问HelloController中定义的TODO列表

1 个答案:

答案 0 :(得分:0)

使用Spring bean而不是像这样的用例使用静态List可能会更好。

@Configuration
public class MyConfig() {

    @Bean
    public List<todos> todos() {
        List<todos> todos = new ArrayList<>();
        //todos.add(...)
    }
}

@Controller
public class SecondController {

    @Autowired
    private List<todos> todos;  

    @RequestMapping(value = "/list-todos", method = RequestMethod.GET)
    public String showTodos(ModelMap model) throws IOException {

        // Use todos 

        return "list-todos";
    }
}