Jordi
Jordi

Reputation: 23277

Spring-boot: @Bean not resolved

I'm getting this error message:

No suitable resolver for argument 0 of type 'org.springframework.context.MessageSource'

This is the related code:

@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;

    }

}

By other hand, I've created this bean:

@Configuration
public class WebServicesConfiguration {

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasenames("messages/exceptions/document");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
}

Any ideas?

Upvotes: 0

Views: 342

Answers (1)

Brother
Brother

Reputation: 2220

I would use the bean, not on the method signature, but injected on the class (constructor or setter method):

@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;
    }
}

Upvotes: 1

Related Questions