Spring ListFactoryBean example

The ‘ListFactoryBean‘ class provides developer a way to create a concrete List collection class (ArrayList and LinkedList) in Spring’s bean configuration file.
Here’s a ListFactoryBean example, it will instantiate an ArrayList at runtime, and inject it into a bean property.

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

Spring’s bean configuration file.



    
        
            
                
                    java.util.ArrayList
                
                
                    
                        1
                        2
                        3
                    
                
            
        
    

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



    
        
            
                1
                2
                3
            
        
    

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:list" 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 [lists=[1, 2, 3]] Type=[class java.util.ArrayList]

You have instantiated ArrayList and injected it into Customer’s lists property at runtime.

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