spring的静态工厂和实例工厂方法

直接上代码吧,好理解

package com.norelax.www.factory;

/**
 * 新闻实体类
 *
 * @author wusong
 * @create 2017-05-29 上午10:29
 **/
public class News {
    String title;
    String content;

    public News(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "News{" +
                "title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}
静态工厂方法实体类:

package com.norelax.www.factory;

import java.util.HashMap;
import java.util.Map;

/**
 * 静态工厂
 *
 * @author wusong
 * @create 2017-05-29 上午10:30
 **/
public class StaticFactory {
    private  static Map newsMap = new HashMap();
    static{
        newsMap.put("news1", new News("标题1", "内容1"));
        newsMap.put("news2", new News("标题2", "内容2"));
    }

    public static  News getNews(String name){
        return newsMap.get(name);
    }
}

实例工厂:

package com.norelax.www.factory;

import java.util.HashMap;
import java.util.Map;

/**
 * 实例工厂方法
 *
 * @author wusong
 * @create 2017-05-29 上午10:51
 **/
public class InstanceFactory {
    Map newsMap=new HashMap();

    public InstanceFactory() {
        newsMap.put("news1",new News("标题1","内容1"));
        newsMap.put("news2",new News("标题2","内容2"));
    }

    public News getNews(String name){
        return newsMap.get(name);
    }
}



静态工厂和实例工厂方法配置:




    
    
        
    

    
    

    
        
    


测试类:

package com.norelax.www.factory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试方法
 *
 * @author wusong
 * @create 2017-05-29 上午10:39
 **/
public class FactoryTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-factory.xml");
        News news1 = (News) applicationContext.getBean("news1");
        System.out.println(news1);

        News news2 = (News) applicationContext.getBean("news2");
        System.out.println(news2);


    }

}

测试结果:

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@69d0a921: startup date [Mon May 29 11:01:30 CST 2017]; root of context hierarchy
五月 29, 2017 11:01:30 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-factory.xml]
News{title='标题1', content='内容1'}
News{title='标题2', content='内容2'}

Process finished with exit code 0



你可能感兴趣的:(Spring)