标签:enc creat 通过 frame get 对象 system void image
工厂模式:实例化对象模式
ref:对某个bean对象的引用
Bean的实例化三种方式:构造器实例化、静态工厂方式实例化、
一、构造器实例化
Beans1.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"> <!-- 通过工厂MyBean2Factory中的createBean方法实例化Bean2 --> <bean id="bean2" class="com.yang.static_factory.MyBean2Factory" factory-method="createBean"></bean> </beans>
Bean1.java
public class Bean1 { }
InstanceTest1.java
public class InstanceTest1 { public static void main(String[] args) { //1.定义配置文件 String xmlPath = "com/yang/constructor/Beans1.xml"; //2.ApplicationContext在加载配置文件时,对bean进行实例化 ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); Bean1 bean =(Bean1) applicationContext.getBean("bean1"); System.out.println(bean); } }
二、静态工厂方式实例化
Beans2.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"> <!-- 通过工厂MyBean2Factory中的createBean方法实例化Bean2 --> <bean id="bean2" class="com.yang.static_factory.MyBean2Factory" factory-method="createBean"></bean> </beans>
Bean2.java
public class Bean2 { }
MyBean2Factory.java
public class MyBean2Factory { //使用自己的工厂创建bean2实例 public static Bean2 createBean(){ return new Bean2(); } }
InstanceTest2.java
public class InstanceTest2 { public static void main(String[] args) { //1.定义配置文件 String xmlPath = "com/yang/static_factory/Beans2.xml"; //2.ApplicationContext在加载配置文件时,对bean进行实例化 ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); Bean2 bean =(Bean2) applicationContext.getBean("bean2"); System.out.println(bean); } }
标签:enc creat 通过 frame get 对象 system void image
原文地址:https://www.cnblogs.com/qiqi-111/p/9103813.html