Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using ReloadableResourceBundleMessageSource in annotations injection

I am using ReloadableResourceBundleMessageSource in my web project, and I inject the class to a servlet, the problem is that I want to inject the class using Spring annotations but it doesn't seem to work? My code is:

my.xml

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>classpath:myList</value>
        </list>
    </property>
    <property name="cacheSeconds" value="1"/>
</bean>

myServletClass.java

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("my.xml");
String message = applicationContext.getMessage(message, null, "Default 
", null);

}

How do I inject the ReloadableResourceBundleMessageSource using annotations?

like image 200
Yo Al Avatar asked Jan 15 '23 02:01

Yo Al


1 Answers

Change the bean to autowire by name

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
    autowire="byName">

   <property name="basenames">
     <list>
       <value>classpath:myList</value>
     </list>
    </property>
    <property name="cacheSeconds" value="1"/>
</bean>

Autowire the Message Source within your Servlet

public Class MyServlet extends HttpServlet{

  @Autowired
  MessageSource messageSource;

  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
       throws ServletException, IOException{
    String message = messageSource.getMessage("test.prop", null, "Default",null);
  }
}

Directory Structure

enter image description here

src/main/resources/myList.properties

test.prop=Hope this helps.

If you are not using Spring MVC you may need to create a Spring application context when starting your application. This can be configured in your Web.xml file using the ContextLoaderListener.

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>
like image 187
Kevin Bowersox Avatar answered Jan 21 '23 22:01

Kevin Bowersox