一、配置文件spring-ioc.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">
<!--1、无参构造-->
<bean id="userEntity1" class="com.zhq.pojo.UserEntity"/>
<!--2、有参构造-->
<bean id="userEntity2" class="com.zhq.pojo.UserEntity">
<constructor-arg name="name" value="猪大宝"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
</bean>
<!--3、实例工厂-->
<bean id="objectFactory" class="com.zhq.pojo.ObjectFactory"/>
<bean id="userEntity3" factory-bean="objectFactory" factory-method="getUserEntity"/>
<!--4、静态工厂-->
<bean id="userEntity4" class="com.zhq.pojo.ObjectFactory" factory-method="getStaticUserEntity"/>
</beans>
二、相关实体类
public class UserEntity {
private String name;
private Integer age;
public UserEntity() {
System.out.println("无参构造函数");
}
public UserEntity(String name, Integer age) {
System.out.println("有参构造函数 name:" + name + "----" + age);
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "UserEntity [name=" + name + ", age=" + age + "]";
}
}
public class ObjectFactory {
/**
*
* @methodDesc: 功能描述:(实例工厂方法)
*/
public UserEntity getUserEntity() {
System.out.println("ObjectFactory getUserEntity");
return new UserEntity("zhangsan", 19);
}
/**
*
* @methodDesc: 功能描述:(静态工厂方法)
*/
static public UserEntity getStaticUserEntity() {
System.out.println("ObjectFactory getStaticUserEntity");
return new UserEntity("static zhangsan", 19);
}
}
三、测试方法
public class SpringIOC {
public static void main(String[] args) {
//加载spring容器
ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring-ioc.xml");
//1、无参构造
UserEntity userEntity1 = (UserEntity) applicationContext.getBean("userEntity1");
System.out.println(userEntity1);
//2、有参构造
UserEntity userEntity2 = (UserEntity) applicationContext.getBean("userEntity2");
System.out.println(userEntity2);
//3、实例工厂
UserEntity userEntity3 = (UserEntity) applicationContext.getBean("userEntity3");
System.out.println(userEntity3);
//3、静态工厂
UserEntity userEntity4 = (UserEntity) applicationContext.getBean("userEntity4");
System.out.println(userEntity4);
}
}