tags:

views:

386

answers:

2

For example, in a Spring config I have a map like this-

<util:map id="someMap"
    map-class="java.util.HashMap"
    key-type="java.lang.String"
    value-type="java.lang.String" >
    <entry key="A" value="Apple" />
    <entry key="B" value="Banana" />
    <entry key="C" value="Cherry" />
    <entry key="D" value="Durian" />     
    <entry key="Default" value="None" />

Now, I have a method-

private String getFruitName(){
     /* result should come from config depending on the 
        value of this.fruit [a fruit type which can be one 
        of the first four keys in the map.] */
}

How do I do that directly with condition set to spring config file rather than getting the value by injecting the key from my method in the class? Can I use conditional statements in the config and maybe pass a parameter to the config?

I don't want to do something like -

if (someMap.containsKey(fruit)){
     fruitName = someMap.get(fruit);
}
+2  A: 

You don't do this with spring.

Spring will provide your beans with configuration and other beans, it is not intended to be used for providing this kind of logic. someMap.get is the way this works, or just inject the appropriate fruit straight into your bean.

krosenvold
+1  A: 

You really shouldn't be trying to do this as you can simply declare the property in your Bean, then use the Spring configuration to set the property on your Bean.

If you must do this for whatever reason, Spring provides a set of interfaces that you may implement to get different levels of access to the Spring configuration. The main interface is ApplicationContextAware. If you implement this interface your Bean will be passed the application context during initialisation (by calling the setApplicationContext(ApplicationContext) method), you can then save the context and call methods on it to programmatically access the context.

To actually access the Map, you would simply call the getBean() method of ApplicationContext (inherited from BeanFactory) passing the id of the Map's bean.

For example:

private String getFruitName(){
    Map someMap = (Map)applicationContext.getBean("someMap");

    return (String)someMap.get(this.fruit);
}

There are a few other interfaces you can implement for more specific access of the Spring context, generally it is preferable to implement the more specific ResourceLoaderAware, ApplicationEventPublisherAware or MessageSourceAware interfaces if you can.

Be aware if you implement any of these interfaces, you no longer have a POJO and are coupled to Spring. Think carefully before doing so.

Rich Seller