给bean一个id是否真的是强制性的

时间:2019-03-04 16:53:06

标签: spring spring-framework-beans

在我被困在这里之前,我认为用id命名一个bean不是强制性的。

dispatcher-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>

messagekeys.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命名吗?

预先感谢:)

1 个答案:

答案 0 :(得分:0)

是的消息资源

  

在加载ApplicationContext时,它会自动搜索上下文中定义的MessageSource bean。 bean必须具有名称messageSource 。如果找到了这样的bean,则对先前方法的所有调用都将委派给消息源。如果找不到消息源,则ApplicationContext尝试查找包含同名bean的父级。如果是这样,它将使用该bean作为MessageSource。如果ApplicationContext找不到任何消息源,则将实例化一个空的DelegatingMessageSource,以便能够接受对上述方法的调用。

在此处documentation