直接上代码,看注释。
创建实体类:
package com.spring.classs;
public class Test { private String name; private String age; public Test(String name, String age) { this.name = name; this.age = age; } public void setName(String name) { this.name = name; } public void setAge(String age) { this.age = age; } public void hellod(){ System.out.println("hello:"+name+"年龄"+age); } @Override public String toString() { return "Test [name=" + name + ", age=" + age + "]"; } }
创建静态的工厂类
package com.spring.beansfactory;
import java.util.HashMap;import java.util.Map;import com.spring.classs.Test;/** * * @author 周永发 *静态工厂方法:直接调用某一个类的静态方法就可以返回Bean 的实例 */public class StaticCarFactory { private static Map<String,Test> testMap = new HashMap<String,Test>(); static{ testMap.put("aud1", new Test("test1","32")); testMap.put("aud2", new Test("test2","15")); } //静态工厂方法 public static Test getCar(String name){ return testMap.get(name); }}在Spring的配置文件中配置
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 配置bean的全类名 --><!-- 通过静态方法配置Bean,不是配置静态工厂的实例,而是配置Bean的实例 --> <!-- class属性:指向静态工厂方法的全类名 factory-method:指向静态工厂方法的名字 constructor-arg:如果工厂方法需要传入参数,则使用Constructor-arg 来配置参数 --> <bean id="test1" class="com.spring.beansfactory.StaticCarFactory" factory-method="getCar"> <constructor-arg value="aud1"></constructor-arg> </bean></beans>
在Main方法中调用
package com.spring.test;
import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.spring.classs.Test;public class Spring1 { public static void main(String[] args){ //1.创建Spring的IOC容器对象 //ApplicationContext 代表IOC容器,且必须要在创建BEAN实例之前 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-Spring.xml"); //2.从IOC容器中获取BEAN Test test =(Test)ctx.getBean("test1"); //3.调用方法 test.hellod(); System.out.println(test); }}
核心思想是在静态工厂中的对象不用实例化!