您的位置:首页 > 编程语言 > Java开发

使用Spring(二)实例化方式(静态工厂,实例工厂)

2016-10-18 13:00 501 查看
1.applicationContext.xml

<?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"> <!-- <bean id="dogBean" class="com.yw.test02.Dog"> </bean> -->

<!-- <alias name="dogBean" alias="dogBean3" /> -->
<!-- createInstance()必须是一个static方法。 -->
<bean id="exampleBean" class="com.yw.test02.Dog" factory-method="createInstance" />

<!-- the factory bean, which contains a method called createInstance() -->
<bean id="myFactoryBean" class="com.yw.test02.Dog">

</bean>
<!-- the bean to be created via the factory bean -->
<bean id="exampleBean2" factory-bean="myFactoryBean"
factory-method="createInstance2" />

</beans>


2.测试类

package com.yw.test02;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class Test02
{
public static void main(String[] args)
{

Resource is = new FileSystemResource("src/com/yw/test02/applicationContext3.xml");
BeanFactory factory = new XmlBeanFactory(is);
//使用 静态工厂方法实例化
Object obj1=factory.getBean("exampleBean");
//使用实例工厂方法实例化
Object obj2=factory.getBean("exampleBean2");

System.out.println("obj1="+obj1);
System.out.println("obj2="+obj2);
}
}


3.Dog类

package com.yw.test02;

public class Dog
{
private String name;

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}
public static Object createInstance()
{
System.out.println("==public static void createInstance()==");
return "createInstance()返回值";
}

public Object createInstance2()
{
System.out.println("==public void createInstance2()==");
return "createInstance2返回值";
}

@Override
public String toString()
{
return "Dog [name=" + name + "]";
}

}


4.运行如图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐