首页 > 解决方案 > 给bean一个id真的是强制性的吗

问题描述

在我被困在这里之前,我认为用 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>

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

用户.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没有 bean的 beanid时,它工作正常。

但是当我使用ReloadableResourceBundleMessageSource没有 bean id 的 bean 时,它不会从messages.properties

当我给ReloadableResourceBundleMessageSourcebean 一个id时,它工作得很好。

所以,我的问题是用 id 命名一个 bean 是强制性的吗?

提前致谢 :)

标签: springspring-framework-beans

解决方案


是的消息资源

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

在这里查看文档


推荐阅读