静态工厂实例化Bean:
static的特点,不需要实例化工厂,直接就通过类名可以访问方法
关键点:
通过静态工厂来对实体类进行管理
必须要有一个静态方法
public class Static_factory {
private static Map<Integer,Kc_class> kc;
static {
kc=new HashMap<Integer, Kc_class>();
kc.put(1, new Kc_class("java"));
kc.put(2, new Kc_class("android"));
kc.put(3, new Kc_class("毛概"));
}
public static Kc_class getKc_class(int id) {
return kc.get(id);
}
}
在spring配置文件中:
必须要配置静态方法
<bean id="kc" class="factory.Static_factory" factory-method="getKc_class">
<constructor-arg value="1"/>
</bean>
在测试中:
获取Bean之后,是赋值给实体类
ClassPathXmlApplicationContext appCon=new ClassPathXmlApplicationContext("applicationContext.xml");
Kc_class c=(Kc_class) appCon.getBean("kc");
System.out.println(c.getKc());
实例(动态)工厂实例化Bean
以实例化工厂的方式管理实体类
public class Dynamic_factory {
private Map<Integer,Kc_class> kc;
public Dynamic_factory(){
kc=new HashMap<Integer, Kc_class>();
kc.put(1, new Kc_class("java"));
kc.put(2, new Kc_class("android"));
kc.put(3, new Kc_class("毛概"));
}
public Kc_class getKc_class(int id) {
return kc.get(id);
}
}
不能直接通过类名来访问方法,所以要创建2个Bean,对于工厂本身要实例化
<bean id="df" class="factory.Dynamic_factory"></bean>
<bean id="kc" factory-bean="df" factory-method="getKc_class">
<constructor-arg value="1"/>
</bean>
ClassPathXmlApplicationContext appCon=new ClassPathXmlApplicationContext("applicationContext.xml");
Kc_class c=(Kc_class) appCon.getBean("kc");
System.out.println(c.getKc());
生命周期
public class BeanLife {
public void init() {
System.out.println("初始化方法开始......");
}
public void destroy() {
System.out.println("摧毁方法开始执行......");
}
}
如果Bean在Spring配置文件中配置了init-method属性,将自动调用其配置的初始化方法。
如果在配置文件中通过destroy-method属性指定了Bean的销毁方法,将调用其配置的销毁方法进行销毁。
<bean id="life" class="beanLife.BeanLife"
init-method="init" destroy-method="destroy" ></bean>
init_method:初始化
destroy-method:摧毁
void test() {
ClassPathXmlApplicationContext appCon=new ClassPathXmlApplicationContext("applicationContext.xml");
Kc_class c=(Kc_class) appCon.getBean("kc");
System.out.println(c.getKc());
appCon.close();
}
初始化appCon则运用初始化方法
appCon.close();则运用摧毁方法