一、配置文件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);
}
}