一、bean 的作用域
在 Spring 中, 可以在 <bean>
元素的 scope 属性里设置 Bean 的作用域.
默认情况下, Spring 只为每个在 IOC 容器里声明的 Bean 创建唯一一个实例, 整个 IOC 容器范围内都能共享该实例:所有后续的 getBean() 调用和 Bean 引用都将返回这个唯一的 Bean 实例.该作用域被称为 singleton, 它是所有 Bean 的默认作用域.
二、使用外部属性文件
Spring 提供了一个 PropertyPlaceholderConfigurer 的 BeanFactory 后置处理器, 这个处理器允许用户将 Bean 配置的部分内容外移到属性文件中. 可以在 Bean 配置文件里使用形式为 ${var} 的变量, PropertyPlaceholderConfigurer 从属性文件里加载属性, 并使用这些属性来替换变量.
1、导入c3p0连接池jar , 注意还要导入相应的辅助包mchange-commons-java.jar
2、编写属性文件db.properties
user=root
password=123456
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/book_db
initPoolSize=5
maxPoolSize=10
3、applicationContext.xml
<!-- 导入资源文件 ,注册property-placeholder 后置处理器-->
<context:property-placeholder location="classpath:properties/db.properties"/>
<!-- 配置C3P0数据源 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="initialPoolSize" value="${initPoolSize}"></property>
<property name="maxPoolSize" value="${maxPoolSize}"></property>
</bean>
4、测试
@Test
public void test() throws SQLException {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext2.xml");
DataSource dataSource = (DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());
}