美文网首页
Spring中加载properties文件

Spring中加载properties文件

作者: Yanl__ | 来源:发表于2019-12-11 16:04 被阅读0次
  1. 在src 下新建xxx.properties 文件
  2. 在spring 配置文件中先引入xmlns:context,在下面添加
    2.1 如果需要记载多个配置文件逗号分割
<context:property-placeholder location="classpath:db.properties"/>
// 多个
<context:property-placeholder location="classpath:db.properties, classpath:log4j.properties"></context:property-placeholder>
  1. 添加了属性文件加载,并且在<beans>中开启自动注入注意的地方(开启全局自动注入,不是单个bean自动注入)
    3.1 SqlSessionFactoryBean 的id 不能叫做sqlSessionFactory
    要改成sqlSessionFactoryBeanName
    3.2 修改
    3.2.1 把原来通过ref 引用替换成value 赋值,自动注入只能影响ref,不会影响value 赋值
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.bjsxt.mapper"></property>
    <property name="sqlSessionFactoryBeanName" value="factory"></property>
</bean>
  1. 在被Spring 管理的类中通过@Value(“${key}”)取出properties 中内容
    4.1 添加注解扫描(需要让Spring知道那个类中有注解)
<context:component-scan base-package="com.steer.service.impl"></context:component-scan>

4.2 在类中添加
4.2.1 key 和变量名可以不相同
4.2.2 变量类型任意,只要保证key 对应的value 能转换成这个
类型就可以.

@Value("${my.demo}")  // my.demo 为在properties中配置的值
private String test;

相关文章