1.用構造器來實例化html
- <bean id="hello2" class="com.hsit.hello.impl.ENhello" />
2.使用靜態工廠方法實例化java
要寫一個bean,bean中定義一個靜態方法,生成bean,配置factory-method指定靜態方法,運行時容器就會自動調用靜態方法生成實例app
beanide
- package com.hsit.hello.impl;
-
- import com.hsit.hello.IHello;
-
- public class CHhello implements IHello {
-
- private String msg;
-
- public void sayHello() {
- System.out.println("中文" + msg);
- }
-
- public String getMsg() {
- return msg;
- }
-
- public void setMsg(String msg) {
- this.msg = msg;
- }
-
- @Override
- public String toString() {
-
- return "Chinese";
- }
-
- public static CHhello createInstance() {
- System.out.println("jingtai");
- return new CHhello();
- }
- }
配置文件測試
- <bean id="hello1" class="com.hsit.hello.impl.CHhello" factory-method="createInstance" lazy-init="true">
-
- <property name="msg" value="哈哈">
- </property>
- </bean>
3.使用實例工廠方法實例化this
要寫兩個bean,一個是要實例化的bean,另外一個是工廠bean。容器先實例化工廠bean,而後調用工廠bean配置項factory-method中指定的方法,在方法中實例化beanspa
工廠bean:
.net
- package com.hsit.hello.impl;
-
- public class ENhelloFactory {
-
- public ENhello createInstance() {
- System.out.println("ENhello工廠");
- return new ENhello();
- }
-
- public ENhelloFactory() {
- System.out.println("chuanjian");
- }
-
- }
要實例化的bean:xml
- package com.hsit.hello.impl;
-
- import com.hsit.hello.IHello;
-
- public class ENhello implements IHello {
-
- @Override
- public void sayHello() {
-
- System.out.println("hello");
- }
-
- @Override
- public String toString() {
-
- return "我是ENhello";
- }
- }
配置文件htm
- <bean id="eHelloFactory" class="com.hsit.hello.impl.ENhelloFactory" />
-
- <bean id="example" factory-bean="eHelloFactory" factory-method="createInstance"/>
測試代碼
- BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
-
- ENhello eNhello = (ENhello) factory.getBean("example");
- System.out.println(eNhello.toString());
-
- factory.getBean("hello1");