学习笔记
spring中三种实例化bean的方式:
一、使用构造器实例化;二、使用静态工厂方法实例化;
三、使用实例化工厂方法实例化。
每种实例化所采用的配置是不一样的:
(applicationContext.xml文件是放在src目录下的)
一、使用构造器实例化:
这种实例化方式要注意:要实例化的类中一定要有一个无参的构造器。
(1)配置spring配置文件。applicationContext.xml的配置
<bean id="personService" class="com.service.PersonServiceBean"></bean>
这种实例化的方式在我们平时的开发中用到的是最多的,因为在xml文件中配置简单并且也不需要额外的工厂类来实现。
id是对象的名称,class是要实例化的类。
(2)通过调用实例化的类即可。
public void instanceSpring(){
//加载spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//调用getBean方法取得被实例化的对象。
PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService");
psb.save();
}
二、使用静态工厂方法实例化
这种方式进行实例化就要具备两个条件:
①要有工厂类及其工厂方法;
②工厂方法是静态的。
(1)首先创建工程类及其静态方法。
com.service.PersonServiceFactory
/*
**创建工厂类
*/
public class PersonServiceFactory {
//创建静态方法
public static PersonServiceBean createPersonServiceBean1(){
//返回实例化的类的对象
return new PersonServiceBean();
}
}
(2)然后再去配置spring配置文件。applicationContext.xml的配置<bean id="personService1" class="com.service.PersonServiceFactory" factory-method="createPersonServiceBean1"></bean>
id是实例化的对象的名称,class是工厂类,也就实现实例化类的静态方法所属的类,factory-method是实现实例化类的静态方法。
<bean id="personService1" class="com.service.PersonServiceFactory" factory-method="createPersonServiceBean1"></bean>
(3)通过调用实例化的类。
public void instanceSpring(){
//加载spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//调用getBean方法取得被实例化的对象。
PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService1");
psb.save();
}
三、使用实例化工厂方法实例化
和上面的方法不同之处在与使用该实例化方式工厂方法不需要是静态的,但是在spring的配置文件中需要配置更多的内容。(1)首先创建工厂类及工厂方法。
com.service.PersonServiceBean
/*
**创建工厂类
*/
public class PersonServiceFactory {
//创建静态方法
public PersonServiceBean createPersonServiceBean2(){
//返回实例化的类的对象
return new PersonServiceBean();
}
}
com.service.PersonServiceBean
/*
**创建工厂类
*/
public class PersonServiceFactory {
//创建静态方法
public PersonServiceBean createPersonServiceBean2(){
//返回实例化的类的对象
return new PersonServiceBean();
}
}
(2)然后配置spring配置文件。
<bean id="personServiceFactory" class="com.service.PersonServiceFactory"></bean>
<bean id="personService2" factory-bean="personServiceFactory" factory-method="createPersonServiceBean2"></bean>
这里需要配置两个bean,第一个bean使用的构造器方法实例化工厂类,第二个bean中的id是实例化对象的名称,factory-bean对应的被实例化的工厂类的对象名称,也就是第一个bean的id,factory-method是非静态工厂方法。
(3)然后调用方法去调用。
public void instanceSpring(){ //加载spring配置文件 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //调用getBean方法取得被实例化的对象。 PersonServiceBean psb = (PersonServiceBean) ac.getBean("personService2"); psb.save();
}