使用Spring(二)实例化方式(静态工厂,实例工厂)
2016-10-18 13:00
501 查看
1.applicationContext.xml
2.测试类
3.Dog类
4.运行如图
<?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.运行如图
相关文章推荐
- 从spring容器中得到bean_使用类构造器实例化_使用静态工厂方法实例化_使用实例工厂方法实例化_例子
- Spring 使用静态工厂方式实例化Bean
- spring创建bean的三种方式-通过构造器,通过静态工厂方法,通过实例工厂方法
- Spring使用实例工厂方法实例化Bean
- Spring使用教程(二)配置bean:静态工厂方法和实例工厂方法
- Spring学习之使用静态工厂方法以及实例工厂方法配置bean
- 先码后看 spring配置bean的几种方式:xml直接配置、静态工厂、实例工厂、factory bean、注解 侵立删
- [原创]java WEB学习笔记102:Spring学习---Spring Bean配置:bean配置方式(工厂方法(静态工厂方法 & 实例工厂方法)、FactoryBean) 全类名
- 7.7.2: Bean实例的创建方式及依赖配置---使用静态工厂方法创建Bean
- spring实例化bean之简单工厂静态方法实例化
- spring Bean使用案例 静态方法方式 和工厂模式
- spring学习小结7_使用工厂方法来配置bean:静态工厂方法和实例工厂方法
- Spring 使用实例工厂方法实例化Bean
- day02_12/12/2016_bean的实例化之静态工厂方式
- Spring与代理模式和实例工厂模式的整合使用
- spring 静态工厂 &实例工厂实例方法 & 实现factorybean接口
- Spring学习笔记九--静态工厂方法和实例工厂方法
- Spring的实例工厂方法和静态工厂方法
- spring注入的方式实现静态方法中使用非静态变量
- spring中通过静态工厂方法获取bean实例化对象