猿问

Spring-boot:@Bean 未解决

我收到此错误消息:


'org.springframework.context.MessageSource' 类型的参数 0 没有合适的解析器


这是相关代码:


@RestControllerAdvice

@Order(Ordered.HIGHEST_PRECEDENCE)

public class ExceptionControllerAdvice {


    @ExceptionHandler({DocumentAlreadyExistsException.class})

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)

    public cat.gencat.ctti.canigo.arch.web.rs.model.Error handleException(MessageSource messageSource, DocumentAlreadyExistsException e) {


        cat.gencat.ctti.canigo.arch.web.rs.model.Error error = new cat.gencat.ctti.canigo.arch.web.rs.model.Error();

        error.setCode(HttpStatus.BAD_REQUEST.value());

        error.setMessage(messageSource.getMessage(e.getLocalizedMessage(), null, null));

        return error;


    }


}

另一方面,我创建了这个 bean:


@Configuration

public class WebServicesConfiguration {


    @Bean

    public MessageSource messageSource() {

        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

        messageSource.setBasenames("messages/exceptions/document");

        messageSource.setDefaultEncoding("UTF-8");

        return messageSource;

    }

}

有任何想法吗?


吃鸡游戏
浏览 183回答 1
1回答

皈依舞

我会使用 bean,而不是在方法签名上,而是在类(构造函数或 setter 方法)上注入:@RestControllerAdvice@Order(Ordered.HIGHEST_PRECEDENCE)public class ExceptionControllerAdvice {    private MessageSource messageSource;    public ExceptionControllerAdvice(MessageSource messageSource) {        this.messageSource = messageSource;    }    @ExceptionHandler({DocumentAlreadyExistsException.class})    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)    public cat.gencat.ctti.canigo.arch.web.rs.model.Error handleException( DocumentAlreadyExistsException e) {        cat.gencat.ctti.canigo.arch.web.rs.model.Error error = new cat.gencat.ctti.canigo.arch.web.rs.model.Error();        error.setCode(HttpStatus.BAD_REQUEST.value());        error.setMessage(messageSource.getMessage(e.getLocalizedMessage(), null, null));        return error;    }}
随时随地看视频慕课网APP

相关分类

Java
我要回答