一共三种方式:
1、调用默认构造函数。
2、利用静态工厂方法创建。
3、利用实例工厂方法创建
====================================
(调用默认构造函数创建对象)
在 cn.google.spring.createobject.method
public class HelloWorld{
public HelloWorld(){
s.o.p("new instance");
}
public void hello(){
s.o.p("hello by spring");
}
}
创建配置文件:applicationContext-createObject-method.xml <bean id="helloWorld_C_M" class="cn.google.spring.sh.ioc.createobject.HelloWorld">
同时配置到 applicationContext.xml 中
public class CreateObjectTest{
@Test
public void testCreateObject(){
//启动spring 容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 从spring容器中把对象取出来
HelloWorld helloWorld = context.getBean("helloWorld_C_M");
//对象调用方法
helloWorld.hello();
}
}
结果: new instance
hello by spring
====================================
(利用静态工厂方法创建,spring调用工厂方法产生对象,但真正创建对象还是由程序员完成)
public class HelloWorldFactory{
public static HelloWorld getInstance(){
return new HelloWorld();
}
}
配置文件applicationContext-createobject-method.xml <!-- factory-method:工厂方法 -->
<bean id="helloFactory" class="cn.google.spring.sh.ioc.createobject.HelloWorldFactory" factory-method="getInstance">
测试方法: public class CreateObjectTest{
@Test
public void testCreateObject(){
//启动spring 容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 从spring容器中把对象取出来
HelloWorldFctory factory = (HelloWorldFactory)context.getBean("helloFactory");
//对象调用方法
factory.hello();
}
}