- "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.xsd">
-
-
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
- <property name="driverClass" value="com.mysql.jdbc.Driver"/>
- <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
- <property name="user" value="root"/>
- <property name="password" value="root"/>
- bean>
- beans>
(1)开启 context 命名空间
(2)使用 context 空间加载 properties 文件
(3)使用属性占位符【${}】读取 properties 文件中的属性
"1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <context:property-placeholder location="classpath*:*.properties" system-properties-mode="NEVER"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> bean> <bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl"> <property name="name" value="${jdbc.driver}"/> bean> beans>
- public class App {
- public static void main(String[] args) {
- //1.加载类路径下的配置文件
- ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
- //2.从文件系统下加载配置文件
- // ApplicationContext ctx = new FileSystemXmlApplicationContext("D:\\CODE\\heima\\spring_10_container\\src\\main\\resources\\applicationContext.xml");
- // BookDao bookDao = (BookDao) ctx.getBean("bookDao");
- // BookDao bookDao = ctx.getBean("bookDao",BookDao.class);
- BookDao bookDao = ctx.getBean(BookDao.class);
- bookDao.save();
- }
- }
- public class AppForBeanFactory {
- public static void main(String[] args) {
- ClassPathResource resource = new ClassPathResource("applicationContext.xml");
- XmlBeanFactory factory = new XmlBeanFactory(resource);
- BookDao bookDao = factory.getBean(BookDao.class);
- bookDao.save();
- }
- }
如果不去获取 bean 对象,打印会发现:(1)BeanFactory 是延迟加载,只有在获取 bean 对象的时候才会去创建(2)ApplicationContext 是立即加载,容器加载的时候就会创建 bean 对象(3)ApplicationContext 要想成为延迟加载,只需要按照如下方式进行配置