gpt4 book ai didi

spring - 在注释注入(inject)中使用 ReloadableResourceBundleMessageSource

转载 作者:行者123 更新时间:2023-12-02 03:33:04 26 4
gpt4 key购买 nike

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

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

}

如何使用注释注入(inject) ReloadableResourceBundleMessageSource

最佳答案

将 Bean 更改为按名称 Autowiring

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

在 Servlet 中 Autowiring 消息源

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

目录结构

enter image description here

src/main/resources/myList.properties

test.prop=Hope this helps.

如果您不使用 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>

关于spring - 在注释注入(inject)中使用 ReloadableResourceBundleMessageSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13265545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com