开发者

Is it possible to inject a bean into a spring form bean

开发者 https://www.devze.com 2022-12-28 05:15 出处:网络
I tried to do it 2 different ways, but neither way worked. @Component public class EmailForm{ ... private QuestionDAO quest开发者_开发知识库ionDAO;

I tried to do it 2 different ways, but neither way worked.

@Component  
public class EmailForm{
...
private QuestionDAO quest开发者_开发知识库ionDAO;
...
@Autowired
public void setQuestionDAO(QuestionDAO questionDAO) {
    this.questionDAO = questionDAO;
}
...

Another way:

@Component  
public class EmailForm implements ApplicationContextAware {
...
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.questionDAO = (QuestionDAO)applicationContext.getBean("questionDAO");
}
...

Neither way results in questionDAO being injected

Form bean is populated by spring:

@RequestMapping(method = RequestMethod.POST)
public String submit(@Valid final EmailForm emailForm, BindingResult result, final Model model) {


The code @RequestMapping(method = RequestMethod.POST) is happening after the form is submitted, not before. In other words, when you do a form submission (HTTP POST) from your Spring Form, it's then calling that submit() method.

To pass any objects to your JSP in Spring MVC, use a org.springframework.web.servlet.ModelAndView instance and call addObject on it.

Then you can actually use plain-old JSTL tags to display the object. For example: <c:out value="${standardizedAddress.streetLine}" />


I think he just wants to know how to auto-inject a spring managed bean into a form POJO that is passed in as a parameter to the controller's handling method. It's not being set -- so there is no "error" perse and doesn't have anything to do with adding objects to the model.

Edit: it looks like this was answered in another thread, here: Custom bean instantiation logic in Spring MVC

0

精彩评论

暂无评论...
验证码 换一张
取 消