我正在使用 Spring MVC 框架。在下面的代码片段中,我是否可以让 Spring 在构造时将 bean 注入(inject)到 MyRequestClass
请求参数中(即使用 @Autowired
或 ApplicationContextAware
接口(interface))?我需要该请求对象来访问我的一个单例 Spring bean,而不必为此目的创建一个实现单例的 ApplicationContextAware
。
到目前为止,我只是遇到 NullPointerExceptions 尝试使用任一方法访问 beanaroo 属性。
@RequestMapping("/**")
@Controller
public class MyController {
@RequestMapping(value = "/mymethod", method = RequestMethod.POST)
public ModelAndView myMethod(@RequestBody MyRequestClass request,
ModelMap modelMap,
HttpServletResponse response) {
...
}
}
例如。
public class MyRequestClass {
@Autowired
private MyInjectedBean beanaroo;
}
我还尝试在我的应用程序上下文文件中定义该类的原型(prototype) bean,但它也没有任何效果。
最佳答案
你可以,使用 @Configurable
和 aspectJ,但如果我是你,我不会。
我只是让 bean 有一个方法,将 MyInjectedBean
作为参数,并从 Controller 调用它。
关于java - bean 中的 @Autowired 属性构造为 MVC 方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5937444/