• spring中@Value("${key}")值原样输出${key}分析与解决


    问题:

    最近发现一个项目中,在类中通过@Value("${key}")获取配置文件中变量值突然不行了,直接输出${key},示例代码如下:

    java类中:

    import org.springframework.beans.factory.annotation.Value;
    
        @Value("${recharge.uri}")
        private String rechargeUri;

    application.properties配置文件中:

    recharge.uri=http://xxx.com/project-name/recharge/fetch.do
    

    applicationContext.xml文件中配置如下:

        <context:property-placeholder location="WEB-INF/application.properties"
                                      ignore-unresolvable="true"/>
    

    web.xml中配置如下:

         <!--Spring ApplicationContext载入,不指定配置文件名则默认为applicationContext.xml -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        
         <!--SpringMVC配置,不指定配置文件名则默认为[servlet-name]-servlet.xml,即dispatcher-servlet.xml -->
      <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>*.htm</url-pattern>
        </servlet-mapping>

    当项目运行时,变量rechargeUri直接输出了${recharge.uri}这个字符串,而不是我配置文件中定义的http://xxx.com/project-name/recharge/fetch.do。
    通过网上查资料,发现如果spring和springmvc并存的情况时,有以下规则:

    1.Spring 允许在父子继承关系中定义多个上下文
    2.applicationContext.xml 文件是为了“根webapp应用上下文”定义bean,也就是说它的上下文是和webapp相关联的
    3.spring-servlet.xml文件是为了一个servlet 应用上下文定义bean,在一个webapp中可以有多个此配置文件
    4.每个springmvc的配置文件[servlet-name]-servlet.xml对应一个web.xml中的servlet定义(例如: 名为spring1的servlet拥有配置文件spring1-servlet.xml, 名为spring2的servlet拥有配置文件spring2-servlet.xml).
    5.当存在多个springmvc配置文件时,他们是不能互相访问的。
    6.SpringMVC的配置文件中可以直接用id引入spring配置文件中定义的bean,但是反过来不可以。

    注:对于ignore-unresolvable="true",当加载多个property-placeholder时,第一个property-placeholder时出现解析不了的占位符会忽略掉,由后面property-placeholder进行解析。

    解决方法:

    对于我这种情况,就是要在dispatcher-servlet.xml中添加application.properties的载入。

    dispatcher-servlet.xml

        <context:property-placeholder location="WEB-INF/application.properties" />

    重新发布项目后,可以正常获取变量值。

    参考文章:https://blog.csdn.net/zuoyixiao/article/details/54288329











  • 相关阅读:
    Python print() 函数
    Python issubclass() 函数
    Python execfile() 函数
    Python basestring() 函数
    QTP自动化测试-点滴-步骤
    qtp自动化测试-条件语句 if select case
    学习心态--笔记
    测试计划小记
    QTP自动化测试-笔记 注释、大小写
    win10 新建文件夹没有了
  • 原文地址:https://www.cnblogs.com/atai/p/10494110.html
Copyright © 2020-2023  润新知