通过Spring读取properties配置文件

灰太狼 2022-05-14 09:39 544阅读 0赞

一般properties文件,用于在代码块中读取,并給变量赋值。但是,Spring可以Bean XML方式定义(注册Bean)中,可以通过${属性名}使用properties文件配置的值。或者在代码中使用@Value注解读取properties的属性值。
所以用途有两种:

1. 用途

1.1. Spinrg的Bean XML定义中,可以通过${属性名}使用properties文件配置的值

首先,必须先加载properties配置文件,方式有两种,如下

方式一:

  1. <!--
  2. 用途1:Spring的xml配置文件中,可以通过${属性名}使用properties文件配置的值
  3. 用途2:可以使用@Value("${属性名}")注解读取properties文件配置的值,再给字段赋值
  4. 方法1:注解在字段上,给字段赋值
  5. 方法2:注解在字段的setter方法中赋值
  6. -->
  7. <context:property-placeholder location="classpath:jdbc.properties"/>

方式二:

  1. <!--
  2. 用途1:Spring的xml配置文件中,可以通过${属性名}使用properties文件配置的值
  3. 用途2:可以使用@Value("${属性名}")注解读取properties文件配置的值,再给字段赋值
  4. 方法1:注解在字段上,给字段赋值
  5. 方法2:注解在字段的setter方法中赋值
  6. -->
  7. <bean id="propertyConfigurer"
  8. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  9. <property name="location">
  10. <value>/WEB-INF/configs/sqlServer.properties</value>
  11. </property>
  12. </bean>

可以清楚的看到,方式一,非常地简洁,但是如果要使用多个properties就可能实现不了,其实可以通过通配符实现,会有点麻烦。

接着,就可以在Bean的定义中,使用properties中的属性值,如下

  1. <bean id="dataSource"
  2. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  3. <property name="driverClassName">
  4. <value>${jdbc.driver}</value>
  5. </property>
  6. <property name="url" >
  7. <value>${jdbc.url}</value>
  8. </property>
  9. <property name="username" >
  10. <value>${jdbc.user}</value>
  11. </property>
  12. <property name="password">
  13. <value>${jdbc.pwd}</value>
  14. </property>
  15. </bean>

1.2. 使用@Value注解读取properties文件配置的值,再给字段赋值

@Value注解是Spring 3.0 之后引入的新特性

@Value的值有三种类型,#{} 、${} 和 #{‘${}‘} ,其实是#{}和${}这两种类型,#{‘${}‘} 这种是前两种的嵌套使用,下面分别介绍

1) #{expression?:default value}

  1. \#\{\} 花括号里面的是SpEL表达式(即Spring Expression Language),?: 前面的是表达式,?: 后面的是默认值,这种方式非常地灵活,可以直接取bean对象的字段值!SpEL表达式的介绍,请看官方参考资料[http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html][http_docs.spring.io_spring_docs_current_spring-framework-reference_html_expressions.html]
  2. 但是,这种方式下,有个缺陷,那就是 properties配置文件中的属性名称不能带点,否则取不到值,会报错

如 file.uploadpath = E:\\360Downloads\\temp , 读取该属性值,就会报错,如下

  1. @Value("#{prop.file.uploadpath}")
  2. private String uploadPath;

    Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field ‘file’ cannot be found on object of type ‘java.util.Properties’ - maybe not public?

    要使用这种类型的Value值,实现方式有两种,如下

    方式一:

  1. <!--
  2. 用途:可以使用@Value("#{prop.属性名}")注解读取properties文件配置的值,再给字段赋值
  3. 方法1:注解在字段上,给字段赋值
  4. 方法2:注解在字段的setter方法中赋值
  5. 注意:@Value("#{prop.属性名}") 中的 prop 是 注册的PropertiesFactoryBean的 Bean ID
  6. -->
  7. <bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  8. <property name="locations">
  9. <array>
  10. <value>classpath:fileupload.properties</value>
  11. </array>
  12. </property>
  13. </bean>

    方式二:

  1. <!--
  2. 用途:可以使用@Value("#{prop.属性名}")注解读取properties文件配置的值,再给字段赋值
  3. 方法1:注解在字段上,给字段赋值
  4. 方法2:注解在字段的setter方法中赋值
  5. 注意:@Value("#{prop.属性名}") 中的 prop 是 注册的PropertiesFactoryBean的 Bean ID
  6. -->
  7. <util:properties id="prop" location="classpath:fileupload.properties"/>

    可以清楚的看到,方式二,非常地简洁,但是如果要使用多个properties就可能实现不了,其实可以通过通配符实现,会有点麻烦。

接下来,看demo

fileupload.properties文件:

  1. name=zengyanhui
  2. age=12

Test.java:

  1. package edu.mvcdemo.service;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Scope;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * @编写人: yh.zeng
  7. * @编写时间:2017-7-26 下午11:04:10
  8. * @文件描述: todo
  9. */
  10. @Component("test")
  11. @Scope("singleton")
  12. public class Test {
  13. @Value("#{prop.name}")
  14. private String name;
  15. @Value("#{prop.age}")
  16. private String age;
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. public String getAge() {
  24. return age;
  25. }
  26. public void setAge(String age) {
  27. this.age = age;
  28. }
  29. }

SpringBeanUtilsTest.java:

  1. package edu.mvcdemo.utils;
  2. import edu.mvcdemo.service.Test;
  3. import junit.framework.TestCase;
  4. /**
  5. * @编写人: yh.zeng
  6. * @编写时间:2017-7-26 下午11:09:38
  7. * @文件描述: todo
  8. */
  9. public class SpringBeanUtilsTest extends TestCase{
  10. public void test1(){
  11. SpringBeanUtils.setFilePath("src/springCfg/applicationContext-base.xml");
  12. Test test = (Test) SpringBeanUtils.getBean("test");
  13. System.out.println("name="+test.getName());
  14. System.out.println("age="+test.getAge());
  15. }
  16. }

程序运行结果:

  1. [INFO][2017-07-27 23:50:59][AbstractApplicationContext:583] - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@b8d805: startup date [Thu Jul 27 23:50:59 CST 2017]; root of context hierarchy
  2. [INFO][2017-07-27 23:50:59][XmlBeanDefinitionReader:317] - Loading XML bean definitions from file [D:\EclipseWorkspace\MavenSpringMvcDemo\src\springCfg\applicationContext-base.xml]
  3. name=zengyanhui
  4. age=12

2)${property:default value}

  1. $\{\}这种值,只用来读取properties配置文件中的属性值, : 前面的是属性名称,: 后面的是默认值。这种类型的值,却可以读取带点的属性值,如 file.uploadpath = E:\\\\360Downloads\\\\temp,可以使用@Value("$\{file.uploadpath\}")读取
  2. 要使用这种方式的Value,有两种实现方式,如下
  3. 方式一:
  1. <!--
  2. 用途1:Spring的xml配置文件中,可以通过${属性名}使用properties文件配置的值
  3. 用途2:可以使用@Value("${属性名}")注解读取properties文件配置的值,再给字段赋值
  4. 方法1:注解在字段上,给字段赋值
  5. 方法2:注解在字段的setter方法中赋值
  6. -->
  7. <bean id="propertyConfigurer"
  8. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  9. <property name="location">
  10. <value>classpath:fileupload.properties</value>
  11. </property>
  12. </bean>

    方式二:

  1. <!--
  2. 用途1:Spring的xml配置文件中,可以通过${属性名}使用properties文件配置的值
  3. 用途2:可以使用@Value("${属性名}")注解读取properties文件配置的值,再给字段赋值
  4. 方法1:注解在字段上,给字段赋值
  5. 方法2:注解在字段的setter方法中赋值
  6. -->
  7. <context:property-placeholder location="classpath:fileupload.properties"/>

可以清楚的看到,方式二,非常地简洁,但是如果要使用多个properties就可能实现不了,其实可以通过通配符实现,会有点麻烦。

下面看demo:

  1. package edu.mvcdemo.service;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Scope;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * @编写人: yh.zeng
  7. * @编写时间:2017-7-26 下午11:04:10
  8. * @文件描述: todo
  9. */
  10. @Component("test")
  11. @Scope("singleton")
  12. public class Test {
  13. @Value("${name}")
  14. private String name;
  15. @Value("${age}")
  16. private String age;
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. public String getAge() {
  24. return age;
  25. }
  26. public void setAge(String age) {
  27. this.age = age;
  28. }
  29. }

程序运行结果:

  1. [INFO][2017-07-27 23:50:59][AbstractApplicationContext:583] - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@b8d805: startup date [Thu Jul 27 23:50:59 CST 2017]; root of context hierarchy
  2. [INFO][2017-07-27 23:50:59][XmlBeanDefinitionReader:317] - Loading XML bean definitions from file [D:\EclipseWorkspace\MavenSpringMvcDemo\src\springCfg\applicationContext-base.xml]
  3. name=zengyanhui
  4. age=12

    (3)#{‘${}‘}

    这种类型的Value值,是#{}里面嵌套${}使用,所以必须按照上述的(1)(2)两种类型的实现方式,配置properties文件,才可以使用这种方式的值

  1. @Value("#{'${age}'}")
  2. private String age;

发表评论

表情:
评论列表 (有 0 条评论,544人围观)

还没有评论,来说两句吧...

相关阅读

    相关 读取Properties配置文件

    通过读取properties文件获取配置项的值在开发中是很常用的,这种方式降低了变量和代码间的耦合,使得非开发人员也可以很容易的对系统的一些配置进行修改,比如配置数据库连接参数