spring实例化bean之简单工厂静态方法实例化

来源:互联网 发布:模拟装修设计软件 编辑:程序博客网 时间:2024/05/21 22:46

PersonDao

public interface PersonDao {}

PersonDaoImpl

public class PersonDaoImpl implements PersonDao{public PersonDaoImpl(){System.out.println("spring通过构造方法来实例化对象");}}

DaoFactory

public class DaoFactory {//利用工厂类的static方法来创建dao实例public static PersonDao createPersonDao(){return new PersonDaoImpl();}}

applicationContext.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/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><!-- spring调用工厂类的静态方法创建bean --><bean id="personDao" class="com.xxc.initBean.two.factory.DaoFactory" factory-method="createPersonDao"></bean></beans>

测试类

public class App {public static void main(String[] args) {ApplicationContext ac = new ClassPathXmlApplicationContext("com/xxc/initBean/two/applicationContext.xml");PersonDao personDao = (PersonDao) ac.getBean("personDao");}}