IOC创建对象的三种方法
第三种:通过工厂的方法创建对象(不多用..)
1.静态工厂
创建一个工厂类:Factory.java
package com.et.factory;
import com.et.bean.Hello;
public class Factory {
public static Hello newInstance(String name){
return new Hello(name);
}
}
beans.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="hello" class="com.et.factory.Factory" factory-method="newInstance">
<constructor-arg index="0" value="elliott"/>
</bean>
</beans>
2.动态工厂
创建一个动态工厂类DynamicFactory .java
package com.et.factory;
import com.et.bean.Hello;
public class DynamicFactory {
public Hello newInstance(String name){
return new Hello(name);
}
}
beans.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="helloFactory" class="com.et.factory.DynamicFactory"></bean>
<bean id="hello" factory-bean="helloFactory" factory-method="newInstance">
<constructor-arg index="0" value="elliott"/>
</bean>
</beans>
两者Hello.java
package com.et.bean;
public class Hello {
private String name;
public Hello(String name){
super();
this.name=name;
}
public void show(){
System.out.println("hello,"+name);
}
}
两者test.java
package com.et.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.et.bean.Hello;
public class Test {
public static void main(String[] args) {
ApplicationContext act=new ClassPathXmlApplicationContext("beans.xml");
Hello hello=(Hello)act.getBean("hello");
hello.show();
}
}
都输出结果:
hello,elliott