ObjectFactory.java
// 工厂,创建对象
public class ObjectFactory {
// 实例方法创建对象
public User getInstance() {
return new User(100,"工厂:调用实例方法");
}
// 静态方法创建对象
public static User getStaticInstance() {
return new User(101,"工厂:调用静态方法");
}
}
bean.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- ###############对象创建############### -->
<!-- 3. 工厂类创建对象 -->
<!-- # 3.1 工厂类,实例方法 -->
<!-- 先创建工厂 -->
<bean id="factory" class="cn.itcast.b_create_obj.ObjectFactory"></bean>
<!-- 在创建user对象,用factory方的实例方法 -->
<bean id="user4" factory-bean="factory" factory-method="getInstance"></bean>
</beans>
输出:
-----User对象创建【带参数构造器】--------
User [id=100, name=工厂:调用实例方法]
========================================================================================================
工厂类调用静态方法创建对象
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- ###############对象创建############### -->
<!-- 3. 工厂类创建对象 -->
<!-- # 3.2 工厂类: 静态方法 -->
<!--
class 指定的就是工厂类型
factory-method 一定是工厂里面的“静态方法”
-->
<bean id="user" class="cn.itcast.b_create_obj.ObjectFactory" factory-method="getStaticInstance"></bean>
</beans>
public class App {
// 测试:对象创建
@Test
public void testIOC() throws Exception {
// 创建IOC容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/b_create_obj/bean.xml");
// 获取容器中的对象
//User user = (User) ac.getBean("user4");
User user = (User) ac.getBean("user5");
System.out.println(user);
}
}
输出:
-----User对象创建【带参数构造器】--------
User [id=101, name=工厂:调用静态方法]