Spring怎么读取properties文件内容
这篇文章主要讲解了"Spring怎么读取properties文件内容",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"Spring怎么读取properties文件内容"吧!
Spring中config属性文件的读取与使用 PropertyPlaceholderConfigurer 注解@Component
1.配置文件:/WEB-INF/configInfo.properties
配置文件内容:
email.host = www.94gleaner.com
email.port = xxx
email.username = gleaner
email.password = xxx
email.sendFrom = 94gleaner@94gleaner.com
2.Spring容器启动时,使用内置bean对属性文件信息进行加载,在bean.xml中添加如下:
property name="location"> /WEB-INF/configInfo.properties
classpath:/opt/demo/config/demo-db.properties file:/opt/demo/config/demo-mq.properties file:/opt/demo/config/demo-remote.properties
3.其它bean中引用,例:
${email.host} ${email.port}
4.JAVA代码中获取方法:创建ConfigInfo.java
@Component("configInfo")public class ConfigInfo {@Value("${email.host}")private String host;@Value("${email.port}")private String port;public String getHost() {return host;}public String getPort() {return port;}}5.代码中调用
@Autowiredprivate ConfigInfo configInfo;public byte[] Test(HttpServletResponse response) {string host = configInfo.getHost();}config.properties配置文件信息
Properties代码
##数据库(mysql|mssql|oracle...)
environment=mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/portal?useUnicode=true&characterEncoding=utf8
jdbc.user=root
jdbc.password=root
#初始化连接(根据实际访问量设置大小)
jdbc.initialSize=10
#最大空闲连接(根据实际访问量设置大小)
jdbc.maxIdle=50
#最小空闲连接(根据实际访问量设置大小)
jdbc.minIdle=10
#最大连接数量(根据实际访问量设置大小)
jdbc.maxActive=200
Spring配置信息(截取部分)
Xml代码
此时,启动会报异常,${jdbc.driver}这样的表达式获取不到properties里面的值,因为MapperScannerConigurer实际是在解析加载bean定义阶段的,这个时候要是设置sqlSessionFactory的话,会导致提前初始化一些类,这个时候,PropertyPlaceholderConfigurer还没来得及替换定义中的变量,导致把表达式当作字符串复制了,解决的办法如下:
方法一:
修改
原理:使用sqlSessionFactoryBeanName注入,不会立即初始化sqlSessionFactory, 所以不会引发提前初始化问题。
方法二:
直接删掉
注意:在没有配置这一行时,必须配置一个以sqlSessionFactory命名的org.mybatis.spring.SqlSessionFactoryBean。
感谢各位的阅读,以上就是"Spring怎么读取properties文件内容"的内容了,经过本文的学习后,相信大家对Spring怎么读取properties文件内容这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!