在注释注入中使用ReloadableResourceBundleMessageSource

Yo *_* Al 4 spring annotations servlets code-injection

ReloadableResourceBundleMessageSource在我的web项目中使用,并且我将类注入到servlet中,问题是我想使用Spring注释注入类但它似乎不起作用?我的代码是:

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>
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

如何注入ReloadableResourceBundleMessageSource使用注释?

Kev*_*sox 9

按名称将bean更改为autowire

<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>
Run Code Online (Sandbox Code Playgroud)

在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);
  }
}
Run Code Online (Sandbox Code Playgroud)

目录结构

在此输入图像描述

SRC /主/资源/ myList.properties

test.prop=Hope this helps.
Run Code Online (Sandbox Code Playgroud)

如果您不使用Spring MVC,则可能需要在启动应用程序时创建Spring应用程序上下文.可以使用ContextLoaderListener在Web.xml文件中配置它.

在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>
Run Code Online (Sandbox Code Playgroud)

  • 在使用ReloadableResourceBundleMessageSource时,不建议在属性路径中存储属性文件.它的文档说 - "由于应用程序服务器通常会缓存从类路径加载的所有文件,因此有必要将资源存储在其他位置(例如,在Web应用程序的"WEB-INF"目录中).否则,类路径中文件的更改将不会反映在应用程序中. (5认同)