zoukankan      html  css  js  c++  java
  • Spring-一个由@ImportResource加载引起的问题

    事情的起因

    项目A中依赖了项目B提供的jar包,其中有一部分配置是从jar以xml形式引入的,xml中要求有类似数据库这样的profile的环境配置。会产生一个很奇怪的问题,通过最外层的application.properties文件定义的属性不能被正常解析。

    目录结构:

    项目A:

    - src/main/resources
    |- application.properties
    |- my.properties
    |- context.xml
    - libraries
    |- B.jar
    |-- my2.properties
    |-- context2.xml
    

    代码:
    application.properties

    my.name=application
    

    my.properties

    my.name=my1
    

    context.xml

    <import resource="classpath:context2.xml"/>
    <context:property-placeholder ignore-unresolvable="true" order="2" location="classpath:my.properties"/>
    <bean id="bean1" class="Bean">
        <property name="name"  value="${my.name}" />
    </bean>
    

    my2.properties

    my.name=my2
    

    context2.xml

    <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	<property name="ignoreUnresolvablePlaceholders" value="true"></property>
    	<property name="location">
    		<value>classpath:my2.properties</value>
    	</property>
    </bean>
    

    运行后,注入的${my.name}只有两种情况,my1 或者my2. 不会是application

    Spring 加载配置文件顺序

    1. application.properties是最先加载的,相同类似的还有application.yml , config/application.properties , application-${profile}.properties
    2. 其他property
    3. @ImportResource引入的xml

    为什么会有这种问题

    如果一个key,user.name 在 application.properties内配置,同时又在xml引用的my.properties文件中引用,会造成在加载xml的Beanfatory中读取到my.properties中的配置,非application.properties的配置

    解决办法

    1. 把application.properties配置到context:property-placeholder/解决,但这个会破坏springboot的profile特性,appliction-${profile}.properties/yml是应对多环境加载的一个优雅方案
    2. my.properties中的信息不配置,默认读取application-${profile}.properties中的,只有1个项目没有问题,涉及jar包传递的不好处理,具有局限性
  • 相关阅读:
    排序算法
    chrome
    2017年末思考
    phpstorm修改创建文件时的默认注释
    男人
    Easyui-Tree和Combotree使用注意事项-sunziren
    Easyui-Treegrid使用注意事项-sunziren
    在生产环境中碰见的JSP木马-sunziren
    JS实现粒子拖拽吸附特效-sunziren
    双向链表的简单Java实现-sunziren
  • 原文地址:https://www.cnblogs.com/jason0529/p/13538790.html
Copyright © 2011-2022 走看看