Employee3Factort.java:
package text.spring._05_instance.instancefactory;
import text.spring._05_instance.staticfactory.Employee2;
/**
* Created by Administrator on 2019/9/3.
*/
public class Employee3Factory {
public Employee3 getObject(){
System.out.println("实例工厂方法创建对象...");
return new Employee3();
}
}
App.java:
package text.spring._05_instance.instancefactory;
import text.spring._05_instance.staticfactory.Employee2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by Administrator on 2019/9/3.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class App {
@Autowired
private ApplicationContext context;
@Test
public void testOld(){
Employee3Factory factory = new Employee3Factory();
Employee3 employee3 = factory.getObject();
System.out.println(employee3);
}
@Test
public void testSpring() throws Exception {
Employee3 employee3 = context.getBean(Employee3.class);
System.out.println(employee3);
}
}
App-context.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="factory" class="text.spring._05_instance.instancefactory.Employee3Factory"></bean>
<bean id="employee3" factory-method="getObject" factory-bean="factory"></bean>
</beans>

本文通过实例演示了如何使用Spring框架的实例工厂方法来创建Bean。通过定义一个工厂类Employee3Factory并实现getObject方法,然后在Spring配置文件中声明工厂Bean和通过factory-bean和factory-method属性指定工厂类及创建Bean的方法,最终在测试类中展示了两种获取Bean的方式:传统工厂模式和Spring框架的依赖注入。
126

被折叠的 条评论
为什么被折叠?



