Spring @@modeldattribute的自动连线
我对Spring非常陌生,我遇到了以下问题 我有下面的控制器,@Autowired在其中工作得很好(试过调试,效果很好) 但是当我提交表单时,注册表单中的@Autowired字段仍然为空 RegistrationForm.java:Spring @@modeldattribute的自动连线,spring,spring-mvc,autowired,modelattribute,Spring,Spring Mvc,Autowired,Modelattribute,我对Spring非常陌生,我遇到了以下问题 我有下面的控制器,@Autowired在其中工作得很好(试过调试,效果很好) 但是当我提交表单时,注册表单中的@Autowired字段仍然为空 RegistrationForm.java: @Component public class RegistrationForm { @Autowired CountryJpaDao countryDao; // ... fields... public Registratio
@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论坛)您在这里混淆了您的概念。对于Spring管理的bean,您可以使用
@Component
和@Autowired
之类的组件,对于用于绑定表单数据的临时、一次性对象,可以使用@modeldattribute
。两者不应混为一谈。Spring将忽略注册表单
上的@组件
和@自动连线
注释,因为它们在该上下文中不合适
像RegistrationForm
这样的类应该表示表单数据,而不是其他。通常,控制器会向RegistrationForm
询问用户ID,然后从DAO本身查看实际的user
对象。如果希望RegistrationForm
查找用户
本身,那么控制器需要在请求用户
对象时手动将DAO提供给RegistrationForm
至于Spring论坛上的那篇帖子,你会注意到它从未收到过回复。这不是一个很好的灵感来源
请注意,我并不是说想要将bean自动连接到表单返回对象中是个坏主意,我只是说Spring不会这样做。如果您在模型上使用@Configurable注释,并在gradle文件上使用aspectJ配置,它会起作用:
compileJava << {
ant.taskdef(
resource: 'org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties',
classpath: configurations.compile.asPath)
ant.iajc(
inpath: sourceSets.main.output.classesDir.absolutePath,
classpath: configurations.compile.asPath,
aspectPath: configurations.aspects.asPath,
destDir: sourceSets.main.output.classesDir.absolutePath
)
}
请粘贴您的spring配置applicationContext.xml或其他文件。检查一下谢谢@skaffman——这就是我的想法。不幸的是,我不能直接将注册表字段“翻译”到用户类。例如,注册表单有三个字段表示出生日期(日、月和年),而用户类使用Datetime。有什么Spring解决方案吗?我创建了RegistrationForm类,其中包含所有作为字符串的表单字段,我希望使用getUser()方法返回一个用户实例(读取RegistrationForm实例字段),但我需要自动连接的Country DAO才能使其工作。非常感谢。
compileJava << {
ant.taskdef(
resource: 'org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties',
classpath: configurations.compile.asPath)
ant.iajc(
inpath: sourceSets.main.output.classesDir.absolutePath,
classpath: configurations.compile.asPath,
aspectPath: configurations.aspects.asPath,
destDir: sourceSets.main.output.classesDir.absolutePath
)
}
@Configurable
public class RegistrationForm
{
...
}