三种bean实例化方式: 默认构造,静态工厂,实例工厂。
默认构造:
<bean id="" class=""></bean> 这种方式就是使用类的默认构造创建实例对象
静态工厂:
常用与spring整合其他框架(工具);静态工厂,用于生成实例对象,所有的方法必须是static.
<bean id="" class="工厂全限定类名" factory-method="静态方法"></bean>
package com.atChina.staticFactory;
public interface SomeService {
void doSome();
}
package com.atChina.staticFactory;
public class SomeServiceImpl implements SomeService {
public SomeServiceImpl(){
System.out.println("SomeServiceImpl...无参构造函数..");
}
@Override
public void doSome() {
System.out.println("doSome业务方法...");
}
// 定义bean的生命始末方法,自定义方法参与到spring创建和销毁对象的过程中。
// 初始化方法
public void startUp(){
System.out.println("bean的初始化方法,可以完成构造方法的功能,给属性赋值,初始化其他对象");
}
// bean销毁之前执行的方法
public void endDown(){
System.out.println("bean对象销毁之前执行的方法,清楚对象,释放内存");
}
}
package com.atChina.staticFactory;
public class MyBeanFactory {
public static SomeService createService(){
return new SomeServiceImpl();
}
}
<bean id="someService2" class="com.atChina.staticFactory.MyBeanFactory" factory-method="createService" />
@Test
public void testStaticFactory(){
String configLocation = "applicationContext.xml"; // 类路径的根目录
ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);
com.atChina.staticFactory.SomeService ss = (com.atChina.staticFactory.SomeService)ctx.getBean("someService2");
ss.doSome();
}
实例工厂
必须先有工厂实例对象,通过实例对象创建对象。提供所有的方法都是非静态的。
package com.atChina.Factory;
public interface SomeService {
void doSome();
}
package com.atChina.Factory;
public class SomeServiceImpl implements SomeService {
public SomeServiceImpl(){
System.out.println("SomeServiceImpl...无参构造函数..");
}
@Override
public void doSome() {
System.out.println("doSome业务方法...");
}
// 定义bean的生命始末方法,自定义方法参与到spring创建和销毁对象的过程中。
// 初始化方法
public void startUp(){
System.out.println("bean的初始化方法,可以完成构造方法的功能,给属性赋值,初始化其他对象");
}
// bean销毁之前执行的方法
public void endDown(){
System.out.println("bean对象销毁之前执行的方法,清楚对象,释放内存");
}
}
package com.atChina.Factory;
public class MyBeanFactory {
public SomeService createService(){
return new SomeServiceImpl();
}
}
<!-- 创建实例工厂 -->
<bean id="myBeanFactory" class="com.atChina.Factory.MyBeanFactory" />
<!-- 从实例工厂获得someService -->
<bean id="someService3" factory-bean="myBeanFactory" factory-method="createService" />
@Test
public void testFactory(){
String configLocation = "applicationContext.xml"; // 类路径的根目录
ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);
com.atChina.Factory.SomeService ss = (com.atChina.Factory.SomeService)ctx.getBean("someService3");
ss.doSome();
}