简体   繁体   中英

How to load two ResourceBundles and inject them separately

I am using Spring for loading localized resource bundles into my application. Here is what I have done.

<bean id="systemMessages" class="o.s.c.s.ResourceBundleMessageSource">
   <property name="basename" value="locale/system"> 
</bean>

<bean id="clientMessages" class="o.s.c.s.ResourceBundleMessageSource">
   <property name="basename" value="locale/client"> 
</bean>

I want to load messages based on the locale in my controller, and I tried both these ways below

@Autowired
@Qualifier("clientMessages")
ResourceBundleMessageSource clientMessages;

@Resource(name="systemMessages")
ResourceBundleMessageSource systemMessages;

EDIT

The application is a JAXRS application and the injection is being tried in a Global Exception Mapper. From the comments I now understand that this class would have been created by the JAXRS container and not Spring ( Code below). How to let Spring know that this injection must work?

import javax.ws.rs.WebApplicationException;

//other imports

public class GlobalWebApplicationException extends WebApplicationException{
   private String systemMessage;
   private String clientMessage;

   //Autowire the multiple resourcebundles

   public GlobalWebApplicationException (String key, Locale locale) {
       // this is where I want to use the injected object fetch the property
   }

   public doSomething(){
       // Business Logic
   }

}

But the injection is not happening and I am getting an NPE. How do I achieve this?

When using Spring and having it do auto wiring using annotations the fields cannot be null . The dependencies need to be satisfied on startup of the application. If that doesn't happen there can be 1 of 2 things wrong

  1. You haven't enabled annotation processing
  2. You aren't using a spring managed bean but are creating instances yourself

For the first option add <context:annotation-config /> to your application context, or if you want to do component scanning add <context:component-scan /> the latter already implies annotation processing.

For the second option you need to make your bean a spring managed bean and use that instead of creating new instances yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM