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使用注释?
按名称将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)
| 归档时间: |
|
| 查看次数: |
27067 次 |
| 最近记录: |