🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**1.工厂方法** ~~~ package com.nobb.factory; import com.nobb.bean.User; public class UserFactory { public static User getUser1(){ User u =new User(); u.setId(1); u.setName("nobb"); return u; } } ~~~ **2.spring配置** ~~~ <bean name="user2" class="com.nobb.factory.UserFactory" factory-method="getUser1"></bean> ~~~ **3.测试代码** ~~~ public class App { public static void main(String[] args){ //类路径Xml应用上下文容器 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); // User user = (User)ac.getBean("user"); // System.out.println(user); User user2 = (User)ac.getBean("user2"); System.out.println(user2); } } ~~~ **4.测试结果(结论:applicationContext会将实例化所有定义的bean)** 调用了无参构造 调用了无参构造 User{id=1, name='nobb'}