}
}
class="example.chapter3.StaticFactoryBean"
factory-method="createRandom" //createRandom方法必须是static的,才能找到
scope="prototype"
/>
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("config.xml"));
System.out.println(factory.getBean("random").toString());
//System.out.println(sfb.createRandom().toString());
}
import java.util.Date;
this.format = format;
}
return new SimpleDateFormat(format).format(new Date());
}
}
<property name="format" value="yyyy-MM-dd HH:mm:ss" />
</bean>
factory-bean="instanceFactoryBean"
factory-method="createTime"
/>
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("config.xml"));
System.out.println(factory.getBean("currentTime"));
}
return new Double(3.14159265358979);
}
return Double.class;
}
return true;
}
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("config.xml"));
System.out.println(factory.getBean("pi"));//返回PiFactoryBean 的工厂方法getObject返回的Double对象实例
//PiFactoryBean p = (PiFactoryBean)factory.getBean("&pi"); //加"&"返回工厂Bean的实例.
//System.out.println(p.getObject());
}
class ExampleBean {
private String string;
public ExampleBean(String string) {
this.string = string;
}
}
class ExampleBeanFactory {
public static ExampleBean createExampleBean(String string) {
return new ExampleBean(string);
}
}
<bean id="exampleBean" class="...ExampleBeanFactory"
scope="prototype"
factory-method="createExampleBean">
<constructor-arg value="default value"/>
</bean>
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"context.xml");
ExampleBean exampleBean =
ExampleBean)context.getBean("exampleBean",
new Object[]{"bla bla"});
exampleBean.write();
}
}
理解Spring中的工厂Bean配置
本文深入探讨了Spring框架中工厂Bean的配置方法,包括静态工厂、实例工厂和实现FactoryBean接口三种类型,并展示了如何在实际场景中动态传递参数。
749

被折叠的 条评论
为什么被折叠?



