飞行的猪哼哼

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Bean2

package com.student.instance.constructor;

public class Bean2 {

}

MyBean2Factory :创建静态工厂

package com.student.instance.constructor;

public class MyBean2Factory {
	public static Bean2 createBean() {
		return new Bean2();
	}

}

beans2: 配置文件

<?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="bean2" class="com.student.instance.constructor.MyBean2Factory" factory-method="createBean">
	</bean>
</beans>

InstanceTest2 测试文件

package com.student.instance.constructor;

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

public class InstanceTest2 {

	public static void main(String[] args) {
		String xmlPath = "com/student/instance/constructor/beans2.xml";
		ApplicationContext applicationContext =new ClassPathXmlApplicationContext(xmlPath);
		Bean2 bean =(Bean2)applicationContext.getBean("bean2");
		System.out.println(bean);

	}

}

运行结果:

十月 13, 2019 2:37:16 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@46f7f36a: startup date [Sun Oct 13 14:37:16 CST 2019]; root of context hierarchy
十月 13, 2019 2:37:16 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/student/instance/constructor/beans2.xml]
com.student.instance.constructor.Bean2@51efea79

解释:
创建一个工厂类(BeanFactory),工厂类里面创建一个返回实体类(Bean2)的方法,配置文件不再写实体类的路径改成工厂类的路径,并且还要用factory-method指明使用的工厂的那个方法创建的。

实际上就是在创建一个类,把创建实体类的操作交给这个类来进行。

posted on 2019-10-13 14:46  飞行的猪哼哼  阅读(40)  评论(0)    收藏  举报