我的 Controller 方法之一需要一个 Spring 托管 bean。由于我在任何其他方法中都不需要它,因此我认为没有必要 Autowiring 它。我已经读到应该避免使用 ApplicationContext.getBean()
,但是有其他选择吗?
如果使用getBean()
是正确的决定,我应该提到创建的bean具有 Autowiring 属性,并且在使用getBeans()<创建它时它们似乎没有被设置
.
代码
@Controller
@RequestMapping("/controller*")
public class Controller {
@RequestMapping
public String get(Model model){
Task task = ApplicationContextHolder.getBean("Task");
task.getA();
return "index";
}
}
public class Task {
@Autowired(required=true)
private Service service;
public List<Object> getA() {
List<Object> list = service.findWhatever(); //service is null
return list;
}
}
完全有可能我没有正确理解所有概念或者我遗漏了一些东西。创建 Task
bean 的最佳方法是什么?
最佳答案
如果 Task
实例由 Spring 管理,那么您确实应该注入(inject)它。正在做
Task task = ApplicationContextHolder.getBean("Task");
遍历整个方法调用堆栈来尝试获取 bean。只要@Autowired
它,你就不会有任何头痛。
请注意
@Autowired(required=true)
private Service service;
期望应用程序上下文中存在另一个Service
bean。
关于java - 一个 Controller 方法中的 Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18001445/