我有一个正在运行的Spring Boot项目 . 我想从外部属性文件中读取一些特定于环境的属性 .
我在启动服务器时提到了配置文件名称和位置,如下所示:
java -jar AllergiesConditions.jar --spring.config.name=application,metadata --spring.config.location=classpath:/,/APPS/SpringBoot/
属性文件加载成功(因为我试图记录数据源bean中的一个外部键值并且它已成功打印) But when i try to access a value using @Value annotation - It returns null.
我的测试类如下:
@Component
public class testclass {
private Logger logger = LogManager.getLogger(testcla.class);
@Value("${sso.server}")
public String sso;
public void test(){
logger.info("sso url is: "+sso); //This sso is logged as null
otherStuff();
}
}
在服务器运行后命中特定API时,将调用此test()函数 .
外部配置文件 - metadata.properties包含以下变量:
sso.server=1234test
编辑:正如在this apparently duplicate question中所建议的那样,我也尝试在主应用程序配置类中添加 @PropertySource(name = "general-properties", value = { "classpath:path to your app.properties"})
并且它加载了文件,但我仍然得到空值 .
Can someone please help in what's going wrong here?? Does the testclass need some specific annotation OR it needs to be a bean or something??
提前致谢 :)
1 回答
感谢M.Deinum的出色表现,节省了我的时间
只是发表他的评论作为答案
事实上
${sso.server}
不能为空 . 如果无法解析${sso.server}
,我的应用程序将在启动时自行中断 .所以显而易见的问题是我在我的控制器中使用
testclass
创建了一个新实例相反,我应该通过在我的控制器中自动装配
testclass
来使用spring托管实例 .