views:

329

answers:

3

I am using this in my application config to specify where to get my messages

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames" value="WEB-INF/properties/messages"/>
 <property name="defaultEncoding" value="UTF-8"/>
</bean>

How do i declare a bean same like this which can be accessible to my java class codes

+1  A: 

You can use this one, instead of creating your own, via:

@Resource(name="messageSource")
private MessageSource messageSource;
Bozho
Where does this look for the messageSource file? My project folder has folders for each subsytem. Each subsytem has its own properties file in its own folder. Or can I set where or what folder it makes the lookup for the file?
cedric
wherever you tell it to look. You can define as much message sources as you need, and inject them, lthough I wouldn't recommend this if they are to many.
Bozho
What do you mean by injecting them? where do I sepcify where it will look up?
cedric
Do I write something like this? @Resource(name="com.package.resource.messages") private MessageSource mesgSource;
cedric
no. You define your messageSource beans in your applicationContext.xml and then inject (you should be familiar with this term) them wherever you want.
Bozho
A: 

Your declaration of the messageSource bean is correct as long as your messages are in WEB-INF/properties/messages in the form of key value pairs.

Now, let's say you want to inject the messageSource in a class called ClassA and you have a setter for it (setMessageSource). All you have to do is have the spring container manage that class as one of it's bean. That means you declare the class as a bean in your applicationContext.xml like so:

<!-- I am not setting the scope of this object as I don't know what it should be. You should do that based on your needs -->
<bean id="classA" class="com.somepath.ClassA">
</bean>

thats it! when the spring container initializes this class it will recognize that it has a field called messageSource of type ReloadableResourceBundleMessageSource and inject the messageSource in the instance of your class.

neesh
A: 

Like @Bozho said after you declare MessageSource Spring will automatically detect the type and inject the properties file it finds at "WEB-INF/properties/messages[.properties]" that you just set up in your context, then you can use it like this messageSource.getMessage("name"[,...]) or you can go the old-fashion way and your bean can implement MessageSourceAware and then you would need to include a public setter for messageSource -- you wouldn't need to explicitly inject the messageSource in this case either Spring would recognize the interface implemented and do the injection automatically for you.

non sequitor