带有环境和spring的java.util.properties

n9vozmp4  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(351)

我有许多类使用java.util.properties类型的资源,但是现在,不同的属性文件有如下环境变量:

com.something.one=AAA1
com.something.two=${MyEnvVar}
com.something.url=http://${myhost}:${myport}/xxx/yyy/zzz

我的课程是:

public class MyTest {

@Resource(name="utilProp")
private Properties  prop;

public void init() {
    System.out.println("var one = "+prop.getProperty("com.something.one"));
    System.out.println("var two = "+prop.getProperty("com.something.two"));
    System.out.println("var url = "+prop.getProperty("com.something.url"));

用这个豆子:

<util:properties id="utilProp" location="classpath:myProp.properties"/>

我有一个结果:

var one = AAA1
var two = ${MyEnvVar}
var url = http://${myhost}:${myport}/xxx/yyy/zzz

如何定义一个与java.util.properties兼容但同时读取环境变量的bean?
比如:

<beans:bean id="utilProp" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <beans:property name="searchSystemEnvironment" value="true"  /> //This not exists here !!! :(
  <beans:property name="locations">
     <beans:list>
       <beans:value>classpath:myProp.properties</beans:value>
     </beans:list>
   </beans:property>
</beans:bean>
c2e8gylq

c2e8gylq1#

我的解决方案是:

import java.io.IOException;
    import java.util.Properties;
    import java.util.Set;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    import org.springframework.beans.factory.config.PropertiesFactoryBean;

    public class MyPropertiesFactoryBean extends PropertiesFactoryBean {

        private  static Pattern p = Pattern.compile("\\$\\{([^\\}]+)\\}");

        @Override
        protected Properties createProperties() throws IOException {
            Properties props = mergeProperties();
            Set keys = props.stringPropertyNames();
            for (String key : keys) {
                String valor =  props.getProperty(key);
                Matcher m = p.matcher(valor); 
                if(m.find()) {
                    m.reset();
                    StringBuffer sb = new StringBuffer();
                    while(m.find()){
                        String envVarName = m.group(1);
                        String envVarValue = System.getenv(envVarName);
                        m.appendReplacement(sb, envVarValue == null ? "" : envVarValue);
                    }
                    m.appendTail(sb);
                    props.setProperty(key,sb.toString());
                }
            }
            return props;
        }
    }
kqlmhetl

kqlmhetl2#

运行应用程序时,请尝试使用下面的正确路径

java org.springframework.boot.loader.PropertiesLauncher --spring.config.location=file:myProp.properties

相关问题