Spring MVC - 无法@Autowire messageSource

时间:2013-09-29 08:55:36

标签: spring-mvc autowired

我有一个自定义异常类,需要从属性文件中读取一些错误消息。但它似乎继续变为空。我甚至尝试添加@Component但仍然无法正常工作

@Component
public class FormValidationFailExceptionHolder {

    @Autowired
    private MessageSource messageSource;

    ...
    public void someMethod(){
        ....
        String message = messageSource.getMessage(errorid, msgargs, Locale.ENGLISH);
        ....
    }
}

这是我的春季配置

....
<context:component-scan base-package="simptex.my" />
....
 <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="useCodeAsDefaultMessage" value="false" />
    <property name="basenames">
        <list>
            <value>classpath:mgmtlabels</value>
            <value>classpath:error</value>
            <value>classpath:PWMResources</value>
        </list>
    </property>
    <property name="defaultEncoding" value="UTF-8" />
</bean>

我甚至尝试在spring config xml中显式声明bean,但仍然返回null

<bean id="formValidationFailException" class="simptex.my.core.exception.FormValidationFailException">
    <property name="messageSource" ref="messageSource" />
</bean>

以下是我调用FormValidationFailException

的方法
public class Foo{
    private HttpSession session;
    ....
    public void fooMethod()  {
        session.setAttribute(CommonSessionKeys.FORM_VALIDATION_EXECEPTION_HOLDER, new FormValidationFailExceptionHolder("roledd", "E0001"));
    }
}

@Controller
public class FooController  {
    @RequestMapping(value = "/xxxx")
    public void fooMethodxxx() {
        Foo foo = new Foo(session);
        foo.fooMethod();
    }
}

1 个答案:

答案 0 :(得分:0)

据我所知,您真正希望实现的是自定义表单验证器。

@Component
public class CustomValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz == FormBean.class;
    }

    @Override
    public void validate(Object target, Errors errors) {
        FormBean bean = (FormBean) target;

        if ( StringUtils.isEmpty( bean.getField() ) ) {
            errors.rejectValue("field", "field.empty");
        }

    }
}

“field.empty”是属性文件中的一个键。

field.empty=Field mustn't be empty

现在在您的控制器中,您需要添加:

@Autowired
private CustomValidator customValidator; 

@InitBinder
protected void initBinder(WebDataBinder binder) {
    if (binder.getTarget() instanceof FormBean) {
        binder.setValidator(customValidator);
    }
}

@RequestMapping(value = "/xxxx", method = RequestMethod.POST)
    public String fooMethodxxx(@ModelAttribute("bean") @Validated FormBean bean, BindingResult result) {
        if ( result.hasErrors() ) {
            prepareModel(model);
            return "form.view";
        }
        return "other.view"
    }

当您发布表单时,它将被验证。要在jsp中向用户显示验证消息,您需要添加:

<%@ taglib prefix="f" uri="http://www.springframework.org/tags/form"%>

<f:errors cssClass="error" path="field"></f:errors>
<f:input path="field" type="text"/>

我认为这是处理自定义验证器的正确方法。