我试图理解为什么messageSource bean在以下代码中被注入null:
@Provider
public class BadRequestExceptionMapper implements ExceptionMapper<BadRequestException>{
@Autowired
MessageSource messageSource;
@Override
public Response toResponse(BadRequestException ex) {
String message = null;
try{
message = messageSource.getMessage(ex.getErrorCode().getErrorKey(),null,null);
}catch(Exception e){
e.printStackTrace();
}
return Response.status(400).entity(message).type("text/plain")
.build();
}
}
下面是我的applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.infonexis" />
<context:annotation-config />
<import resource="applicationPersistence.xml" />
<import resource="applicationService.xml" />
<import resource="applicationContext-datasource.xml" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename">
<value>MessageResources_en_US</value>
</property>
<property name="cacheSeconds" value="1"/>
</bean>
</beans>
我试图在自定义异常映射器类中自动连接MessageSource bean,但它被注入null,以前当我从ClassPathXmlApplicationContext加载上下文时,它正在工作,如下所示:
@Provider
public class BadRequestExceptionMapper implements ExceptionMapper<BadRequestException>{
@Override
public Response toResponse(BadRequestException ex) {
String message = null;
try{
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
MessageSource messageSource =
(MessageSource)context.getBean("messageSource");
message = messageSource.getMessage(ex.getErrorCode().getErrorKey(),null,null);
}catch(Exception e){
e.printStackTrace();
}
return Response.status(400).entity(message).type("text/plain")
.build();
}
}
我已经尝试了以下
实现org.springframework.context.MessageSourceAware接口
给BadRequestExceptionMapper类添加@Component注释
尝试注入ReloadableresourceBundleMessageSource而不是使用MessageSource接口
但一切都失败了。
上下文组件扫描设置正确。如何才能正确地注入MessageSource
我认为你的@Provider在你的web.xml中定义了一些上下文侦听器,它可能在spring应用程序上下文侦听器之前启动。
尝试将Spring listener org.springframework.web.context.ContextLoaderListener放在Web Services listener(如com.sun.xml.ws.transport.http.servlet.WSServletContextListener)或任何JAX-RS servlet listener(如jersey)之前。