无法使用属性文件中的@Value("${database.name}") 获取值
Unable to get value using @Value("${database.name}") from properties file
@Configuration
public class Config {
@Value("${database.name}")
private String dbname;
public String dbname2;
public Config(){
dbname2 = dbname;
System.out.println(" ::::: Got Data from properties file Successfully ::::: " + dbname2);
}
}
@Service
public class MainService {
@Autowired
Config config;
public String getPropertiesData(){
String data = "Properties Data is " + config.dbname2;
return data;
}
}
application.properties 文件中的数据:
server.port=8081
database.name=azurecosmosDB
堆栈跟踪 启动应用程序时低于:
. ____ _ __ _ _
/\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.0.RELEASE)
2019-11-06 13:10:21.106 INFO 13328 --- [ restartedMain] com.example.demo.DemoApplication : Starting DemoApplication on LP-5CD921DY4D with PID 13328 (C:\Users\BalajiChe\Desktop\STOMP\demo\target\classes started by BalajiChe in C:\Users\BalajiChe\Desktop\STOMP\demo)
2019-11-06 13:10:21.113 INFO 13328 --- [ restartedMain] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2019-11-06 13:10:21.247 INFO 13328 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-11-06 13:10:21.247 INFO 13328 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-11-06 13:10:27.732 INFO 13328 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2019-11-06 13:10:27.763 INFO 13328 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-11-06 13:10:27.763 INFO 13328 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.27]
2019-11-06 13:10:28.335 INFO 13328 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-11-06 13:10:28.336 INFO 13328 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 7089 ms
::::: Got Data from properties file Successfully ::::: null
2019-11-06 13:10:30.395 INFO 13328 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2019-11-06 13:10:31.212 INFO 13328 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-11-06 13:10:31.382 INFO 13328 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2019-11-06 13:10:32.063 INFO 13328 --- [ restartedMain] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2019-11-06 13:10:32.128 INFO 13328 --- [ restartedMain] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2019-11-06 13:10:32.168 INFO 13328 --- [ restartedMain] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
2019-11-06 13:10:32.523 INFO 13328 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2019-11-06 13:10:32.529 INFO 13328 --- [ restartedMain] com.example.demo.DemoApplication : Started DemoApplication in 12.299 seconds (JVM running for 14.621)
此外, 成功从属性获取数据到文件 :::: null ---- 将出现在控制台中。必须在启动应用程序时从属性文件中获取值。有什么方法可以获取值吗?
首先是旁注:
Spring boot只有放入
才能自动读取application.properties
src/main/resources
src/main/resources/config
文件夹
确保它确实存在。
现在真正的问题是:
您正在尝试访问 属性 构造函数中的 而这不是 spring 的工作方式:
Spring 首先创建对象(通过调用其构造函数),然后才注入其字段。
所以你有两种方法:
选项 1:
为你的 beans 使用构造函数注入(我看到你使用 @Configuration
但这个建议更适合真正的 beans,在那里更有意义):
@Component
class MyClass {
public MyClass(@Value({"db.name"} String dbName) {
....
}
}
选项 2:
不在构造函数中检查,而是在构造后检查,或者如果您在谈论 @Bean
注释方法中的配置:
@Configuration
public class MyConfig {
@Value("${db.name}")
private String dbName;
@Bean
public SomeBean someBean() {
// here dbName should be accessible
return new SomeBean (dbName)
}
// alternatively you can inject dbName like this:
@Bean
public SomeOtherBean someOtherBean(@Value("${db.name}") String dbName) {
return new SomeOtherBean(dbName);
}
}
这是因为在Spring
中字段是在默认构造函数调用后初始化的,因此您应该只在调用构造函数后访问它,试试这个:
@PostConstruct
public void postConstructorMethod(){
dbname2 = dbname;
System.out.println(" ::::: Got Data from properties file Successfully ::::: " + dbname2);
}
正如@Mustahsan 所说,您无法访问在构造函数中注入到字段中的值,因为注入发生在构造之后。
但是,如果您想使用构造函数,那么您可以使用构造函数注入来代替字段注入,这通常被认为是更好的做法:
@Configuration
public class Config {
public String dbname2;
public Config(@Value("${database.name}") String dbname){
dbname2 = dbname;
System.out.println(" ::::: Got Data from properties file Successfully ::::: " + dbname2);
}
}
@Configuration
public class Config {
@Value("${database.name}")
private String dbname;
public String dbname2;
public Config(){
dbname2 = dbname;
System.out.println(" ::::: Got Data from properties file Successfully ::::: " + dbname2);
}
}
@Service
public class MainService {
@Autowired
Config config;
public String getPropertiesData(){
String data = "Properties Data is " + config.dbname2;
return data;
}
}
application.properties 文件中的数据:
server.port=8081
database.name=azurecosmosDB
堆栈跟踪 启动应用程序时低于:
. ____ _ __ _ _
/\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.0.RELEASE)
2019-11-06 13:10:21.106 INFO 13328 --- [ restartedMain] com.example.demo.DemoApplication : Starting DemoApplication on LP-5CD921DY4D with PID 13328 (C:\Users\BalajiChe\Desktop\STOMP\demo\target\classes started by BalajiChe in C:\Users\BalajiChe\Desktop\STOMP\demo)
2019-11-06 13:10:21.113 INFO 13328 --- [ restartedMain] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2019-11-06 13:10:21.247 INFO 13328 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-11-06 13:10:21.247 INFO 13328 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-11-06 13:10:27.732 INFO 13328 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2019-11-06 13:10:27.763 INFO 13328 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-11-06 13:10:27.763 INFO 13328 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.27]
2019-11-06 13:10:28.335 INFO 13328 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-11-06 13:10:28.336 INFO 13328 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 7089 ms
::::: Got Data from properties file Successfully ::::: null
2019-11-06 13:10:30.395 INFO 13328 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2019-11-06 13:10:31.212 INFO 13328 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-11-06 13:10:31.382 INFO 13328 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2019-11-06 13:10:32.063 INFO 13328 --- [ restartedMain] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2019-11-06 13:10:32.128 INFO 13328 --- [ restartedMain] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2019-11-06 13:10:32.168 INFO 13328 --- [ restartedMain] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
2019-11-06 13:10:32.523 INFO 13328 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2019-11-06 13:10:32.529 INFO 13328 --- [ restartedMain] com.example.demo.DemoApplication : Started DemoApplication in 12.299 seconds (JVM running for 14.621)
此外, 成功从属性获取数据到文件 :::: null ---- 将出现在控制台中。必须在启动应用程序时从属性文件中获取值。有什么方法可以获取值吗?
首先是旁注:
Spring boot只有放入
才能自动读取application.properties
src/main/resources
src/main/resources/config
文件夹
确保它确实存在。
现在真正的问题是:
您正在尝试访问 属性 构造函数中的 而这不是 spring 的工作方式:
Spring 首先创建对象(通过调用其构造函数),然后才注入其字段。
所以你有两种方法:
选项 1:
为你的 beans 使用构造函数注入(我看到你使用 @Configuration
但这个建议更适合真正的 beans,在那里更有意义):
@Component
class MyClass {
public MyClass(@Value({"db.name"} String dbName) {
....
}
}
选项 2:
不在构造函数中检查,而是在构造后检查,或者如果您在谈论 @Bean
注释方法中的配置:
@Configuration
public class MyConfig {
@Value("${db.name}")
private String dbName;
@Bean
public SomeBean someBean() {
// here dbName should be accessible
return new SomeBean (dbName)
}
// alternatively you can inject dbName like this:
@Bean
public SomeOtherBean someOtherBean(@Value("${db.name}") String dbName) {
return new SomeOtherBean(dbName);
}
}
这是因为在Spring
中字段是在默认构造函数调用后初始化的,因此您应该只在调用构造函数后访问它,试试这个:
@PostConstruct
public void postConstructorMethod(){
dbname2 = dbname;
System.out.println(" ::::: Got Data from properties file Successfully ::::: " + dbname2);
}
正如@Mustahsan 所说,您无法访问在构造函数中注入到字段中的值,因为注入发生在构造之后。
但是,如果您想使用构造函数,那么您可以使用构造函数注入来代替字段注入,这通常被认为是更好的做法:
@Configuration
public class Config {
public String dbname2;
public Config(@Value("${database.name}") String dbname){
dbname2 = dbname;
System.out.println(" ::::: Got Data from properties file Successfully ::::: " + dbname2);
}
}