创建对象的几种方式
- 调用无参数构造器
- 调用有参数构造器
- 工厂
静态方法
<bean id=”’ class=”” factory-method=””/>
非静态方法
<bean id=”factory” class=”..”>
<bean id=”” factory-bean=” factory” factory-method=”实例方法” />- 反射
案例
- beam.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="user" class="com.xxjqr.spring01.create_obj.User"></bean>
-->
<!-- 调用有参构造器
<bean id="user" class="com.xxjqr.spring01.create_obj.User">
<constructor-arg index="2" type="int" value="22"></constructor-arg>
<constructor-arg index="0" type="String" value="丁昌江"></constructor-arg>
<constructor-arg index="1" type="String" value="男"></constructor-arg>
</bean>
-->
<!-- 工厂模式-静态方法
<bean id="user" class="com.xxjqr.spring01.create_obj.UserFactory" factory-method="getStaticInstance"></bean>
-->
<!-- 工厂模式-非静态方法 -->
<bean id="factory" class="com.xxjqr.spring01.create_obj.UserFactory"></bean>
<bean id="user" factory-bean="factory" class="com.xxjqr.spring01.create_obj.User" factory-method="getInstance"></bean>
</beans>
类
@Data
@AllArgsConstructor
public class User {
private String name;
private String sex;
private int age;
}
public class UserFactory {
public static User getStaticInstance(){
return new User("单身汉","男",20);
}
public User getInstance(){
return new User("单身汉","男",20);
}
}
测试类
public class App {
private ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml",App.class);
@Test
public void testUser() {
User user = (User) ac.getBean("user");
System.out.println(user);
}
}