一、实例化bean
该文将使用三种不同方式:构造器、静态工厂、实例工厂。进行创建Java对象。
项目结构:
pojo包下的Java类
public class User {
}
public class Customer {
}
factory包下的Java类
public class CustomerFactory {
public Customer getInstance() {
return new Customer();
}
}
public class UserFactory {
public static User getInstance() {
return new User();
}
}
xml配置文件
注意:使用第三种:实例工厂方法实例化bean对象时,需要先将实例工厂bean创建出来,然后再到 factory-bean属性中取引用实例的工厂的id,factory-method属性中引用工厂的方法。
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 第一种:使用构造器实例化bean对象 -->
<bean id="user1" class="com.shengjava.pojo.User"></bean>
<!-- 第二种:静态工厂方法实例化bean对象 -->
<bean id="user2" class="com.shengjava.factory.UserFactory"
factory-method="getInstance"/>
<!-- 第三种:实例工厂方法实例化bean对象 -->
<bean id="customer"
factory-bean="customerFactory"
factory-method="getInstance"/>
<!-- 需要创建出实例工厂 -->
<bean id="customerFactory" class="com.shengjava.factory.CustomerFactory"/>
</beans>
测试类:
public class UserTest {
@Test
public static void main(String[] args) {
// create and configure beans(现在我们的对象都是Spring进行管理了,我们可以去Spring的容器ApplicationContext中获取。context:上下文、环境的意思)
ApplicationContext context = new ClassPathXmlApplicationContext("pojos.xml");
// retrieve configured instance(从上下文context中获取对象)
User user1 = context.getBean("user1", User.class);
User user2 = context.getBean("user2", User.class);
Customer customer = context.getBean("customer", Customer.class);
System.out.println(user1);
System.out.println(user2);
System.out.println(customer);
}
}
测试结果:
com.shengjava.pojo.User@23282c25
com.shengjava.pojo.User@7920ba90
com.shengjava.pojo.Customer@6b419da
可以看出以上三种方式已经创建好了Java类。
这里没有参考官方文档中的:1.3.2. Instantiating Beans 。因为我感觉官方文档中这个章节怪怪的。
相关
我的该分类的其他相关文章,请点击:【Spring + Spring MVC + MyBatis】文章目录