三种实例化bean的方法
情形如下:我们有一个PersonDaoImpl类,需要交给spring容器进行管理
PersonDao.java
package com.chris.dao;public interface PersonDao {public abstract void save();}
PersonDaoImpl.java
package com.chris.dao.impl;import com.chris.dao.PersonDao;public class PersonDaoImpl implements PersonDao {/* (non-Javadoc) * @see com.chris.dao.PersonDao#save() */@Overridepublic void save(){System.out.println("save....");}}
?
方法一:通过类默认构造器进行实例化
?????在spring配置文件beans.xml中配置如下代码
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd">....<bean name="personDaoBean" name="code">package com.chris.factory;import com.chris.dao.PersonDao;import com.chris.dao.impl.PersonDaoImpl;public class PersonDaoFactory {//静态工厂方法public static PersonDao getInstence(){return new PersonDaoImpl();}}
?在spring配置文件beans.xml中配置如下代码
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd">....<bean name="personDaoBean" factory-method="getInstence"/> <!--class属性为静态工厂类 factory-method为静态工厂方法--> ....</beans>
?方法三:通过实例工厂进行实例化
实例工厂类PersonDaoFactory.java
package com.chris.factory;import com.chris.dao.PersonDao;import com.chris.dao.impl.PersonDaoImpl;public class PersonDaoFactory {public PersonDao getInstence(){return new PersonDaoImpl();}}
?
?在spring配置文件beans.xml中配置如下代码
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><!--首先配置实例工厂,将实例工厂交给容器管理 --><bean name = "personDaoFacotry" class = "com.chris.factory.PersonDaoFactory"/><!--factory-bean中填写实例工厂在容器中的名称 factory-method为工厂中获取对象实例方法--><bean name = "personDaoBean" factory-bean="personDaoFacotry" factory-method="getInstence"/></beans>
??
经过上述三种方法任选一种进行配置后,我们就可以从spring容器中获取我们需要的PersonDaoImpl对象了
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");PersonDao personDao = (PersonDao) applicationContext.getBean("personDaoBean");personDao.save();
?