IT序号网

properties之spring-boot 属性占位符

kerrycode 2024年06月03日 编程语言 48 0

我无法弄清楚为什么我无法在 spring-boot 中将值注入(inject)到我的 application.properties 文件中。外部属性到 logging.file 变量中。我有一个 application.properties 文件,看起来像这样

logging.file=${mylogfile} 
server.port=${myport} 

对应的Spring-boot应用类

@PropertySources({ 
@PropertySource("file:///c:/myfolder/externalprops.properties"), 
}) 
 
@Configuration 
@EnableAutoConfiguration 
@ComponentScan 
public class Application { 
 
public static void main(String[] args) throws Exception { 
    SpringApplication.run(Application.class, args); 
} 
} 

和外部属性文件

mylogfile=myoutput.log 
myport=8060 

当我运行我的 spring-boot 1.0.2.REL 应用程序时,每次我尝试将 mylogfile 注入(inject) application.properties 的 logging.file 属性时都会出现以下异常

Exception in thread "main" java.lang.IllegalArgumentException: Could not resolve placeholder 'mylogfile' in string value "${mylogfile}" 
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174) 

请注意,如果我自己注入(inject)服务器端口号,我在注入(inject)和启动应用程序时不会遇到任何问题。

我在这个问题上一直在兜圈子,不知道我做错了什么。

请您参考如下方法:

我认为您不能使用 @PropertySource 将值注入(inject)“application.properties”——后者必须在任何 @Configuration 之前被解析并准备好使用> 被阅读,甚至被了解。您的外部属性可以放在“${user.dir}/application.properties”中,我认为这将实现您想要做的事情。


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!