Spring4学习笔记(七):bean的作用域和使用外部属性文件
来源:互联网 发布:淘宝上的1号胶囊是什么 编辑:程序博客网 时间:2024/06/01 08:29
一、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=rootpassword=123456driverClass=com.mysql.jdbc.DriverjdbcUrl=jdbc:mysql://localhost:3306/book_dbinitPoolSize=5maxPoolSize=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()); }
阅读全文
0 0
- Spring4学习笔记(七):bean的作用域和使用外部属性文件
- Spring4.0学习笔记-bean之间的关系,作用域以及使用外部属性文件
- Spring4笔记----使用外部属性文件配置 bean
- spring学习小结4——bean 的作用域 和引入外部属性文件
- Spring4深入理解IOC&DI02----Bean配置--自动装配、bean之间的继承与依赖、使用外部属性文件
- Spring4----使用注解方式配置bean和bean的属性
- spring_bean的作用域,spring使用外部属性文件和spring_SpEL(三)
- Spring全家桶(二)Bean之间的关系、自动装配、作用域和使用外部文件
- spring学习总结(六):IOC & DI 配置Bean之作用域、加载外部属性文件、SPEL
- Spring4笔记----bean的作用范围
- J2EE系列之Spring4学习笔记(六)--IOC详解(bean之间的关系,bean的作用范围)
- 12.笔记JAVA Spring框架学习————Bean使用外部属性文件
- J2EE之Spring中Bean的作用域、外部属性文件、SpEL
- Spring4的知识应用总结(三)——Bean之间的关系和作用域
- Spring4.0学习笔记003——Bean的配置一(基于XML文件)
- Spring4.0学习笔记004——Bean的配置二(基于XML文件)
- Spring4.0学习笔记005——Bean的配置三(基于XML文件)
- Spring学习笔记03--bean的作用域(scope属性)
- C# Datagridview checkbox
- C语言求a+aa+aaa+...
- Ubuntu上安装Wine 2.6
- [RK3288][Android6.0] 调试笔记 --- USB Camera旋转图像方法
- Andrew Ng的 Machine Learning 读书笔记 Lecture 4(数据归一化,调参)
- Spring4学习笔记(七):bean的作用域和使用外部属性文件
- android开发实现打电话的两种效果
- Arcgis发布服务出错显示:The server is not ready for publishing.
- Flask-SocketIO简介
- JS 随笔
- MFC+OPENCV3.0显示摄像头画面
- 【简记】大规模Web开发技术(第十四章)
- mybaits如何批量更新数据库
- ftp服务器搭建