Spring MapFactoryBean example

The ‘MapFactoryBean‘ class provides developer a way to create a concrete Map collection class (HashMap and TreeMap) in Spring’s bean configuration file.
Here’s a MapFactoryBean example, it will instantiate a HashMap at runtime,, and inject it into a bean property.

package com.mkyong.common;
import java.util.Map;
public class Customer { 
    private Map maps; 
    //...
}

Spring’s bean configuration file.



    
        
            
                
                    java.util.HashMap
                
                
                    
                        
                        
                        
                    
                
            
        
    

Alternatively, you also can use util schema and to achieve the same thing.



    
        
            
                
                
                
            
        
    

Remember to include the util schema, else you will hit the following error

Caused by: org.xml.sax.SAXParseException: The prefix "util" for element "util:map" is not bound.

Run it…

package com.mkyong.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App { 
    public static void main( String[] args ) { 
        ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml"); 
        Customer cust = (Customer)context.getBean("CustomerBean"); 
        System.out.println(cust); 
    }
}

Ouput

Customer [maps={Key2=2, Key1=1, Key3=3}] Type=[class java.util.HashMap]

You have instantiated a HashMap and injected it into Customer’s map property at runtime.

你可能感兴趣的:(Spring MapFactoryBean example)