在Spring中注入配置文件

Posted szs00szs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Spring中注入配置文件相关的知识,希望对你有一定的参考价值。

在项目工程中的可能会存在修改的属性,一般都是配置在外置的配置文件(.properties,.json,*.xml…)中。在使用时通过IO流读取并解析。 Spring框架对此进行了封装可以很方便的进行加载解析。

例如,存在文件 project.properties

# user
user.name=admin
user.pass=root

将配置文件注入spring存在两种方式:

1. 在spring的配置文件中注入

    <!-- 注入配置文件 -->
    <context:property-placeholder location="classpath:project.properties" file-encoding="UTF-8" system-properties-mode="NEVER"/>

2. 在spring容器中声明一个类org.springframework.beans.factory.config.PropertyPlaceholderConfigurer中注入

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
               <value>classpath:project.properties</value>
             </list>
        </property>
    </bean>

使用属性:

    @Value(value = "$user.name")
    private String name;

    @Value(value = "$user.pass")
    private String pass;

    // test value inject: [name=admin],[pass=root]
    System.out.println("test value inject: [name=" + name + "],[pass=" + pass + "]");

以上是关于在Spring中注入配置文件的主要内容,如果未能解决你的问题,请参考以下文章

在Spring中注入配置文件

如何调用spring配置文件手动注入的bean

spring4.X,如何在代码中使用注解来注入属性文件里配置的值

Spring 扫描注入

spring-自动加载配置文件使用属性文件注入

【Spring源码配置文件解析】2. xml注入配置信息 & @Value