javaweb中spring实例化bean三方式之实例工厂法

基于上一篇的项目配置,请浏览上一篇的一些基础 的配置
https://blog.csdn.net/weixin_43319279/article/details/103086312
1:创建实体类

package com.instantiationFactory;

public class Personl {
	public void say() {
		System.out.println("Personl say");
	}

}

2:创建实例工厂类

package com.instantiationFactory;

public class BeanFactoryTest {
	public BeanFactoryTest(){
		System.out.println("实例化工程");
	}
	
	public  Personl createBean() {
		return new Personl();
	}

}

3:配置spring.xml

 <bean id="beanFactoryTest" class="com.instantiationFactory.BeanFactoryTest"/>
 <bean id="personl" factory-bean="beanFactoryTest" factory-method="createBean"/>

通过实例化工厂beanFactoryTest,通过beanFactoryTest来实例化personl,与前面的构造方法和静态工厂的方法不同,构造方法和静态工厂方法是通过class来实例化对象的。

4:创建测试类

package com.instantiationFactory;

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

public class Demo {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
		Personl personl = (Personl) applicationContext.getBean("personl");
		personl.say();
	}
}

结果为:
在这里插入图片描述

总结
spring是一个类容器,所有类的产生和消亡都是由spring来控制的,spring框架是为了简化应用程序的开发。学习了spring三种方法的实例bean,基本的思想是通过实例化ApplicationContext 来完成对 springIOC容器的创建和实例化,使用springIOC促进程序的松耦合性 ,spring可以理解为一个大的工厂, bean就是你要他生产产品。

发布了80 篇原创文章 · 获赞 15 · 访问量 1871

猜你喜欢

转载自blog.csdn.net/weixin_43319279/article/details/103095308