<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url" value="jdbc:mysql://localhost:3306/oa?characterEncoding=gb2312" /> <property name="username" value="root" /> <property name="password" value="root" /> <property name="maxActive" value="100" /> <property name="maxIdle" value="30" /> <property name="maxWait" value="1000" /> <property name="defaultAutoCommit" value="true" /> <property name="removeAbandoned" value="true" /> </bean> </beans>
保存爲applicationContext.xml 構造BeanFactory能夠用以下方式:
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); reader.loadBeanDefinitions("classpath:applicationContext.xml"); DataSource ds = (DataSource)beanFactory.getBean("dataSource"); System.out.println(ds);
上述代碼中beanFactory其實進行了兩大步,首先加載BeanDefinition,而後實例化Bean,內部是採用大體以下的方式作的:
AbstractBeanDefinition dataSourceBeanDefinition = new RootBeanDefinition(BasicDataSource.class,true); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition("dataSource", dataSourceBeanDefinition); DataSource ds = (DataSource)factory.getBean("dataSource"); BeanWrapper dsBeanWrapper = new BeanWrapperImpl(ds); dsBeanWrapper.setPropertyValue("driverClassName", "com.mysql.jdbc.Driver"); dsBeanWrapper.setPropertyValue("url","jdbc:mysql://localhost:3306/oa?characterEncoding=gb2312"); dsBeanWrapper.setPropertyValue("username","root"); dsBeanWrapper.setPropertyValue("password", "root"); dsBeanWrapper.setPropertyValue("maxActive",100); dsBeanWrapper.setPropertyValue("maxIdle", 30); dsBeanWrapper.setPropertyValue("maxWait", 1000); dsBeanWrapper.setPropertyValue("defaultAutoCommit",true); dsBeanWrapper.setPropertyValue("removeAbandoned", true); System.out.println(ds.getConnection());先讀取BeanDefinition,再實例化bean,設置屬性可經過BeanWrapperImpl進行設置,比通常的反射技術要好的多。