1,创建实体类User
package com.songyan.demo1; /** * 要创建的对象类 * @author sy * */ public class User { private String name; private int age ; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
2,创建生产对象的工厂类
改工厂类必须有一个静态的返回值为“要生产的对象的类型”
package com.songyan.staticfactory; import com.songyan.demo1.User; /** * 创建User对象的工厂类 * @author sy * */ public class UserFactory { /** * 该方法必须是static的 * @return 工厂要创建的对像 */ public static User createUser() { return new User(); } }
3,配置bean对象
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "> 3 4 <!--通过构造函数创建对象 --> 5 <bean id="userid" class="com.songyan.demo1.User"></bean> 6 7 <!--通过静态工厂创建对象 --> 8 <!--通过 com.songyan.staticfactory.UserFactory类中的createUser方法创建名为user2的对象 --> 9 <bean name="user2" class="com.songyan.staticfactory.UserFactory" factory-method="createUser"></bean> 10 </beans>
4,测试类
1 package com.songyan.Test; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 import com.songyan.demo1.User; 7 8 public class Client { 9 public static void main(String[] args) { 10 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); 11 /*User user=(User)applicationContext.getBean("userid"); 12 System.out.println(user);*/ 13 User user2=(User)applicationContext.getBean("user2"); 14 System.out.println(user2); 15 16 } 17 }
5,结果
来源:https://www.cnblogs.com/excellencesy/p/9103622.html