在我被困在这里之前,我认为命名一个带有id的bean并不是强制性的。
调度员servlet.xml中
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan
base-package="com.springMVC.*"></context:component-scan>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/Views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename">
<value>/WEB-INF/messagekeys</value>
</property>
</bean>
message可以是.properties
NotEmpty.user1.name = UserName cannot be empty
Size.user1.name = Name should have a length between 6 and 16
Pattern.user1.name = Name should not contain numeric value
Min.user1.age = Age cannot be less than 12
Max.user1.age = Age cannot be more than 60
NotNull.user1.age = Please enter your age
NotEmpty.user1.email = email cannot be left blank
Email.user1.email = email is not valid
NotEmpty.user1.country = Enter valid country
user.Java
package com.springMVC.model;
import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("request")
public class User {
@NotEmpty
@Size(min=6,max=16)
@Pattern(regexp = "[^0-9]+")
private String name;
@Min(value=12)
@Max(value=60)
@NotNull
private Integer age;
@NotEmpty
@Email
private String email;
@NotEmpty
private String country;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setEmail(String email) {
this.email = email;
}
public void setCountry(String country) {
this.country = country;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public String getEmail() {
return email;
}
public String getCountry() {
return country;
}
}
当我使用豆InternalResourceViewResolver
没有豆id
,它工作正常。
但是当我使用没有bean id的bean ReloadableResourceBundleMessageSource
时,它不会从messages.properties
呈现错误消息
当我给ReloadableResourceBundleMessageSource
豆一个id
,它的工作完美。
所以,我的问题是命名一个id为必需的bean吗?
提前致谢 :)
是的消息资源
加载ApplicationContext时,它会自动搜索在上下文中定义的
MessageSource
bean。 bean必须具有名称messageSource。如果找到这样的bean,则对前面方法的所有调用都被委托给消息源。如果未找到任何消息源,ApplicationContext将尝试查找包含具有相同名称的bean的父级。如果是,则将该bean用作MessageSource。如果ApplicationContext找不到任何消息源,则会实例化一个空的DelegatingMessageSource,以便能够接受对上面定义的方法的调用。
在这里查看documentation