Backslash (\) in .proprties file is being ignored by Spring's 'Environment' variable

你离开我真会死。 提交于 2019-12-07 14:48:01

问题


I am trying to load a config.proprties file data in a Spring @Configuration java class using @PropertySource and Environment variable.

Example: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html Issue is, I have a property which has value like:

     serverName = abc\xyz

When I read this property by using method,

     String server= env.getProprty("serverName");
     System.out.print(server);

Value is printed as "abcxyz".

Please note that, I tried using double backslash like,

     serverName = abc\\xyz

but still it is simply ignoring \ from the value string. Also I can not use forward slash in place of backslash.

Can you help me in fixing it? Thanks in advance!!


回答1:


This is a real ugly hack, but you can try and use unicode escape sequence for the symbol "\" which is "\u005c" so instead of string value "abc\xyz" use "abc\u005cxyz". But then again it will translate it to "abc\xyz" and then consider "\" as a start of escape symbol. So if first one doesn't work you can try to replace "abc\\xyz" with "abc\u005c\u005cxyz". See if the first or second option works for you. But in truth, I am surprised that simple escaping "\\" didn't solve your problem. Also if all fails try this "abc\\\\xyz" - this is double escaping.




回答2:


I used spring 3.1.4-RELEASE and it worked if values in properties file contains '\\'. Like serverName = abc\\xyz

package com.test;   

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration;    
import org.springframework.context.annotation.PropertySource;   
import org.springframework.core.env.Environment;    

@Configuration  
@PropertySource("app.properties")   
public class AppConfig {    

    @Autowired  
    Environment env;

    @Bean   
    public String myBean() {    
        System.out.println(env.getProperty("serverName"));
        return new String(env.getProperty("serverName"));   
    }   
}



回答3:


Instead of backward slash, I stored them with forward slash in config file.

While reading, I replaced them with double backward slash.

SourcePath=C:/Users/Barani/Documents/SampleData/MyInputFile.txt

    Path currentRelativePath = Paths.get("");
    String filePath = currentRelativePath.toAbsolutePath().toString() + "/config.properties";
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream(filePath);
    props.load(fis);
    sourcePath = props.getProperty("SourcePath").replace("/", "\\\\");

This worked correctly for me.



来源:https://stackoverflow.com/questions/37858207/backslash-in-proprties-file-is-being-ignored-by-springs-environment-vari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!