小编典典

@Autowired为@ModelAttribute

spring-mvc

我是Spring的新手,遇到以下问题。

我有以下控制器,其中@Autowired可以完美运行(尝试调试并且可以正常运行)。

@Controller
@RequestMapping(value = "/registration")
@SessionAttributes("rf")
public class RegistrationController
{
    @Autowired
    UserJpaDao userDao;

    @RequestMapping(method = RequestMethod.GET)
    @Transactional
    public String setupForm(Model model) throws Exception
    {
        model.addAttribute("rf", new RegistrationForm());
        return "registration";
    }

    @RequestMapping(method = RequestMethod.POST)
    @Transactional
    public String submitForm(@ModelAttribute("rf") RegistrationForm rf, Model model) throws Exception
    {
        // ...

        User user = rf.getUser();
        userDao.save(user);

        // ...

        return "registration";
    }
}

但是,当我提交表单时,我的RegistrationForm中的@Autowired字段仍然为空。

RegistrationForm.java:

@Component
public class RegistrationForm
{
    @Autowired
    CountryJpaDao countryDao;

    // ... fields...

    public RegistrationForm()
    {

    }

    @Transactional
    public User getUser() throws InvalidUserDataException
    {
        //...

        Country c = countryDao.findByCode("GB"); // Throws java.lang.NullPointerException

        // ...
    }

    // ... getters/setters...
}

这是表单的HTML / JSTL:

<form:form method="POST" modelAttribute="rf">
    ...
</form:form>

谁能帮我?

谢谢。

(受SpringSource论坛上的这篇文章启发)


阅读 311

收藏
2020-06-01

共1个答案

小编典典

您在这里混淆了您的概念。您可以对Spring管理的bean 使用like
@Component和,对于用于绑定表单数据的瞬态,一次性对象也可以使用此类对象。不应将两者混为一谈。您的和上的注释将被Spring忽略,因为它们不适用于该上下文。@Autowired``@ModelAttribute``@Component``@Autowired``RegistrationForm

像这样的类RegistrationForm应该代表表单数据,而别无其他。通常,控制器会询问RegistrationForm用户ID,然后User从DAO本身查看实际对象。如果要RegistrationForm查找User自身,则控制器需要RegistrationForm在请求User对象时手动提供DAO

就Spring论坛上的帖子而言,您会注意到它从未得到答案。这不是从中获取灵感的好来源。

请注意,我并不是说希望将bean自动装配到Form Back对象中不是一个好主意,我只是说Spring不会这样做。

2020-06-01