实例工厂方式实例化Bean
程序员文章站
2022-05-21 22:57:14
...
Bean3:实体类
package com.student.instance.constructor;
public class Bean3 {
}
bean3 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- services -->
<bean id="myBean3Factory" class="com.student.instance.constructor.MyBean3Factory"></bean>
<bean id="bean3" factory-bean="myBean3Factory" factory-method="createBean">
</bean>
</beans>
Bean3Factory :工厂类
package com.student.instance.constructor;
public class MyBean3Factory {
public MyBean3Factory() {
System.out.println("哈哈,我的Bean3正在实例化!!");
}
public Bean3 createBean() {
return new Bean3();
}
}
InstanceTest3 :测试类
package com.student.instance.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InstanceTest3 {
public static void main(String[] args) {
String xmlPath = "com/student/instance/constructor/bean3.xml";
ApplicationContext applicationContext =new ClassPathXmlApplicationContext(xmlPath);
Bean3 bean =(Bean3)applicationContext.getBean("bean3");
System.out.println(bean);
}
}
输出结果:
十月 13, 2019 2:56:31 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org[email protected]46f7f36a: startup date [Sun Oct 13 14:56:31 CST 2019]; root of context hierarchy
十月 13, 2019 2:56:31 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/student/instance/constructor/bean3.xml]
哈哈,我的Bean3正在实例化!!
[email protected]
解释:
因为静态方法,外部可以直接通过对象名.方法名的方式进行调用,所以配置的时候只需要一个<bean> ;代码如下:
<bean id="bean2" class="com.student.instance.constructor.MyBean2Factory" factory-method="createBean"></bean>
这里只需要指明类地址和方法名就能进行调用,但是实例工厂不能直接通过这个方式调用,需要先用一个<Bean>将实例工厂加载到配置文件,然后再通过另一个<bean>指明实例工厂的哪种方法。
代码如下:
<bean id="myBean3Factory" class="com.student.instance.constructor.MyBean3Factory"></bean>
<bean id="bean3" factory-bean="myBean3Factory" factory-method="createBean">
</bean>