Unable to receive message from MessageSource outside controller

Everything works fine when I try to receive messages in the @Controller class, but when I try to achieve this in the @Service or @Component class I get the following error:

org.springframework.context.NoSuchMessageException: 
No message found under code 'email.ativacao.title' for locale 'pt_BR'.

My controller:

@Controller
public class TestController {

    @Autowired
    TestService service;

    @Autowired
    TestComponent component;

    @Autowired
    private MessageSource message;

    @RequestMapping(value = "/send", method = RequestMethod.GET)
    public String go() {

            String message = message.getMessage
                   ("email.ativacao.title", null, new Locale("pt", "BR"));

            service.getMessage();

            component.getMessage();

            return "signsucess";
     }

}

My service:

@Service
public class TestService {

    @Autowired
    private MessageSource message;

    public void getMessage() {
        //Error
        String message = message.
            getMessage("email.ativacao.title", null, new Locale("pt", "BR"));
    }

}

My component:

@Component
public class TestComponent {

    @Autowired
    private MessageSource message;

    public void getMessage() {
        //Error
        String message = message.
            getMessage("email.ativacao.title", null, new Locale("pt", "BR"));
    }

}

My configuration:

<!-- i18n -->
<mvc:interceptors>
    <bean class="org.springframework.web.servlet.i18n.
                LocaleChangeInterceptor" p:paramName="lang"/>
</mvc:interceptors>

<!-- Mesage Source Config -->       
<bean id="messageSource"
    class="org.springframework.context.support.
        ReloadableResourceBundleMessageSource" p:fallbackToSystemLocale="true" >
    <property name="basename" value="WEB-INF/i18n/messages" />
</bean>

<!-- Mapeia o cookie que irá salvar as opções de idioma -->
<bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver"
    id="localeResolver" p:cookieName="locale"/>

MessageSource is not null for both @Service and @Component, but they cannot receive the message (Exception above). My properties:

WebContent / WEB-INF / i18n

  • messages_pt_BR
  • messages_en_US

I really can't find the problem. Any suggestion to solve this? Thank.

+5
source share
1 answer

From what you described, I assume that the bean controller and messageSource were declared in the same context. so they can find each other.

bean bean , messageSource.

. one.xml two.xml.

, , .

+10

All Articles