[英]@Value not working in Spring @Configuration
Need help, where is the issue?需要帮助,问题出在哪里?
I have a configuration class which is loading properties as我有一个配置类,它正在加载属性
WebConfig.java配置文件
@Configuration
@PropertySource(value={"classpath:application.properties"})
class WebConfig extends WebMvcConfigurerAdapter{
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
I have another configuration class where I am trying to use the properties as我有另一个配置类,我试图将这些属性用作
MyServerConfig.java我的服务器配置文件
@Configuration
class MyServerConfig {
@Value("${server.url}")
private String url;
...
}
application.properties应用程序属性
server.url=http://localhost:8080/test/abc
But getting:但是得到:
java.lang.IllegalArgumentException: Could not resolve placeholder 'server.url'. java.lang.IllegalArgumentException:无法解析占位符“server.url”。
Don't know what is missing here?不知道这里缺少什么? Any thoughts?有什么想法吗?
Use the @PropertyScan
annotation in the class where a certain property will be used:在将使用某个属性的类中使用@PropertyScan
注释:
@Configuration
@PropertyScan("classpath:application.properties")
class MyServerConfig {
@Value( "${server.url}" )
private String url;
}
For getting the values for your @Value
variables, the application.properties
is not needed to be configured in any special way because this file is always scanned.要获取@Value
变量的值,不需要以任何特殊方式配置application.properties
,因为始终会扫描此文件。 So remove the @PropertySource
annotation and PropertySourcesPlaceholderConfigurer
bean.所以删除@PropertySource
注释和PropertySourcesPlaceholderConfigurer
bean。
These are used if you want to add other .properties
files (eg constants.properties
, db-config.properties
).如果您想添加其他.properties
文件(例如constants.properties
、 db-config.properties
),可以使用这些文件。
So just remove those and try to run your application again所以只需删除那些并尝试再次运行您的应用程序
Very important:很重要:
Make sure you scan the class that uses the @Value
annotation (If your BootApplication is in some package instead of the 'main' package, add the proper @SpringBootApplication(scanBasePackages = { "com.my.project" })
annotation).确保扫描使用@Value
注释的类(如果您的 BootApplication 位于某个包中而不是“main”包中,请添加正确的@SpringBootApplication(scanBasePackages = { "com.my.project" })
注释)。
Make sure your application.properties
is on your classpath.确保您的application.properties
在您的类路径上。
Bonus If you are using spring profiles (eg: prod
, dev
), you can also have application-prod.properties
and application-dev.properties
files that will be scanned and included depending on which profile you are running.奖励如果您使用的是 spring 配置文件(例如: prod
、 dev
),您还可以拥有application-prod.properties
和application-dev.properties
文件,这些文件将根据您运行的配置文件进行扫描和包含。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.