2017-08-25 74 views
0

我使用Spring(沒有彈簧啓動)。我想構建可使用默認配置(資源文件夾中的logback.xmlapplication.properties)或-Dconfig.folder=/path/to/custom/external/directorylogback.xmlapplication.properties in/path/to/custom/external/directory)運行的獨立應用程序。當使用-Dconfig.folder參數運行應用程序參數AppConfig應該從外部目錄加載logback和屬性。外部化屬性和logback春天

是否有任何使外部文件夾像資源文件夾一樣行事?

如果沒有,這是什麼常見的解決方案?

我當前實現(使用默認的資源文件夾只):

App.java

public class App { 

    public static void main(String[] args) { 
     ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 

     SampleAction p = context.getBean(SampleAction.class); 
     p.performTask(); 
    } 
} 

AppConfig.java

@ComponentScan 
@PropertySource("classpath:application.properties") 
class AppConfig { 

    @Bean 
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    } 
} 

SampleAction.java

@Component 
public class SampleAction { 
    private final Logger logger = LoggerFactory.getLogger(this.getClass()); 

    @Value("${sample.prop}") 
    private String sampleProp; 

    public void performTask(){ 
     logger.debug(sampleProp); 
    } 
} 

logback.xmlapplication.properties是不相關的問題

+0

難道我滿意的回答你的問題?如果是,請隨時接受。如果不是,請解釋爲什麼不能讓我改進答案。 –

+0

我在一天前添加了一條評論,關於我缺少的內容:)基本上,我不知道在哪裏放置該Java代碼的InputStream配置,以便讓我的logback配置可用asap – ilovkatie

+0

請參閱我的編輯。如果你對Spring一無所知,你需要先做好功課。當你遇到特殊問題時,我們會盡力幫助你,我們不會做你的工作。 –

回答

1

與其他答案建議不同,如果在中使用file前綴,因爲它無法從jar中加載默認的application.properties而被搞砸了。你應該做的是:

@PropertySource("${config.folder:'classpath:'}/application.properties") 
public class AppConfig 

對於logback.xml

@Value("${config.folder}:") 
private String configFolder; 

InputStream = Optional.of(new ClassPathResource(configFolder + "/logback.xml")) 
    .filter(r -> r.exists()) 
    .orElse(new ClassPathResource("classpath:/logback.xml")) 
    .getInputStream(); 

在這兩種情況下,我放棄優先於命令行參數在默認的打包文件。當然,我沒有編譯上述內容,所以可能會出現拼寫錯誤或小錯誤,但您明白了。

編輯

由於OP聲稱自己不明白的地方運行上面的代碼 -

public class AppConfig { 
    @PostConstruct 
    void init() { 
     // init logback here 
    } 
} 
+0

我想知道我應該把這個logback配置放在哪裏:1.使用正確的日誌記錄選項asap 2.保持我的應用程序在拆分邏輯和配置方面的清潔。任何建議? – ilovkatie

+0

@ilovkatie'src/main/resources' –

+0

我的意思是InputStream的登錄配置:> – ilovkatie

0

對於的log4j.xml

-Dlog4j.configuration=C:\neon\log4j.xml作爲VM參數

在main()方法:

String filename = System.getProperty("log4j.configuration"); 
DOMConfigurator.configure(filename); 

對於外部屬性文件:

-Dext.prop.dir=C:\neon作爲VM參數

在你的AppConfig類變化會像

從外部位置
@PropertySource("file:///${ext.prop.dir}/application.properties") 
public class AppConfig{ 
} 
與VM參數如下且各文件

運行App類會使用

-Dlog4j.configuration=C:\neon\log4j.xml -Dext.prop.dir=C:\neon