Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get message from MessageSource outside Controller

Tags:

java

spring

Everything works fine when I try to get messages in a @Controller class, but when I try to achieve the same in a @Service or @Component class I receive 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 config:

<!-- 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 on both @Service and @Component, but they're not able to get 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? Thanks.

like image 506
raonirenosto Avatar asked Jan 31 '13 13:01

raonirenosto


1 Answers

From what you were describing, I guess controller bean and messageSource were declared in same context. so then can find each other.

if your service bean and controller bean are not declared in same context, your service cannot find the messageSource.

same context doesn't mean same file. your one.xml could include two.xml.

anyway, if it worked for you, it's good.

like image 65
Kent Avatar answered Nov 02 '22 10:11

Kent