Spring Boot @Value 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39047333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Boot @Value Properties
提问by user6641655
I have a Spring Boot application and in one of the classes, I try to reference a property from the application.properties file using @Value
. But, the property does not get resolved. I have looked at similar posts and tried following the suggestions, but that didn't help. The class is:
我有一个 Spring Boot 应用程序,在其中一个类中,我尝试使用 .properties 文件从 application.properties 文件中引用一个属性@Value
。但是,财产没有得到解决。我看过类似的帖子并尝试遵循建议,但这没有帮助。班级是:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class PrintProperty {
@Value("${file.directory}")
private String fileDirectory;
public void print() {
System.out.println(fileDirectory);
}
}
I have the property file.directory in application.properties
. I have other fields as well.
我在application.properties
. 我也有其他领域。
回答by u7737578
I had the same problem like you. Here's my error code.
我和你有同样的问题。这是我的错误代码。
@Component
public class GetExprsAndEnvId {
@Value("hello")
private String Mysecret;
public GetExprsAndEnvId() {
System.out.println("construct");
}
public void print(){
System.out.println(this.Mysecret);
}
public String getMysecret() {
return Mysecret;
}
public void setMysecret(String mysecret) {
Mysecret = mysecret;
}
}
This is no problem like this, but we need to use it like this:
像这样没有问题,但我们需要像这样使用它:
@Autowired
private GetExprsAndEnvId getExprsAndEnvId;
not like this:
不是这样的:
getExprsAndEnvId = new GetExprsAndEnvId();
Here, the field annotated with @Value is null because Spring doesn't know about the copy of GetExprsAndEnvId that is created with new and didn't know to how to inject values in it.
在这里,用@Value 注释的字段为空,因为 Spring 不知道用 new 创建的 GetExprsAndEnvId 的副本,也不知道如何在其中注入值。
回答by Jesse
Make sure your application.properties file is under src/main/resources/application.properties. Is one way to go. Then add @PostConstruct as follows
确保您的 application.properties 文件位于 src/main/resources/application.properties 下。是一种方法。然后添加@PostConstruct如下
Sample Application.properties
示例 Application.properties
file.directory = somePlaceOverHere
Sample Java Class
示例 Java 类
@ComponentScan
public class PrintProperty {
@Value("${file.directory}")
private String fileDirectory;
@PostConstruct
public void print() {
System.out.println(fileDirectory);
}
}
Code above will print out "somePlaceOverhere"
上面的代码将打印出“somePlaceOverhere”
回答by Peter S.
I′d like to mention, that I used spring boot version 1.4.0 and since this version you can only write:
我想提一下,我使用的是 spring boot 1.4.0 版本,因为这个版本你只能写:
@Component
public class MongoConnection {
@Value("${spring.data.mongodb.host}")
private String mongoHost;
@Value("${spring.data.mongodb.port}")
private int mongoPort;
@Value("${spring.data.mongodb.database}")
private String mongoDB;
}
Then inject class whenever you want.
然后随时注入类。
EDIT:
编辑:
From nowadays I would use @ConfigurationPropertiesbecause you are able to inject property values in your POJOs. Keep hierarchical sortabove your properties. Moreover, you can put validationsabove POJOs attributes and so on. Take a look at the link
从现在开始,我将使用@ConfigurationProperties,因为您可以在 POJO 中注入属性值。在您的属性上方保持分层排序。此外,您可以将验证放在 POJO 属性等之上。看一下链接
回答by rajadilipkolli
To read the values from application.properties we need to just annotate our main class with @SpringBootApplication
and the class where you are reading with @Component or variety of it. Below is the sample where I have read the values from application.properties
and it is working fine when web service is invoked. If you deploy the same code as is and try to access from http://localhost:8080/helloyou will get the value you have stored in application.properties for the key message.
要从 application.properties 读取值,我们只需要@SpringBootApplication
使用 @Component 或各种类型来注释我们的主类和您正在读取的类。下面是我从中读取值的示例,application.properties
并且在调用 Web 服务时它工作正常。如果您按原样部署相同的代码并尝试从http://localhost:8080/hello访问,您将获得存储在 application.properties 中的关键消息值。
package com.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
@Value("${message}")
private String message;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping("/hello")
String home() {
return message;
}
}
Try and let me know
尝试让我知道
回答by Nallamachu
I had the similar issue and the above examples doesn't help me to read properties. I have posted the complete class which will help you to read properties values from application.properties file in SpringBoot application in the below link.
我有类似的问题,上面的例子不能帮助我阅读属性。我已经在下面的链接中发布了完整的类,它将帮助您从 SpringBoot 应用程序中的 application.properties 文件中读取属性值。
Spring Boot - Environment @Autowired throws NullPointerException
回答by Simon Gibbs
You haven't included package declarations in the OP but it is possible that neither @SpringBootApplication
nor @ComponentScan
are scanning for your @Component
.
您尚未在 OP 中包含包声明,但可能既没有@SpringBootApplication
也没有@ComponentScan
扫描您的@Component
.
The @ComponentScan
Javadoc states:
该@ComponentScan
Javadoc中说明:
Either
basePackageClasses
orbasePackages
(or its aliasvalue
) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
可以指定
basePackageClasses
orbasePackages
(或其别名value
)来定义要扫描的特定包。如果没有定义特定的包,将从声明该注解的类的包开始扫描。
ISTR wasting a lot of time on this before and found it easiest to simply move my application class to the highest package in my app's package tree.
ISTR 之前在这方面浪费了大量时间,并发现将我的应用程序类简单地移动到我的应用程序包树中最高的包是最简单的。
More recently I encountered a gotcha were the property was being read before the value insertion had been done. Jesse's answer helped as @PostConstruct
seems to be the earliest you can read the inserted values, and of course you should let Spring call this.
最近,我遇到了一个问题,即在值插入完成之前正在读取属性。Jesse 的回答很有帮助,因为它@PostConstruct
似乎是您最早可以读取插入值的答案,当然您应该让 Spring 调用它。
回答by Dormouse
Your problem is that you need a static
PropertySourcesPlaceholderConfigurer
Bean definition in your configuration. I say static with emphasis, because I had a non-static one and it didn't work.
您的问题是您的配置中需要一个Bean 定义。我强调静态,因为我有一个非静态的,但它不起作用。static
PropertySourcesPlaceholderConfigurer
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
回答by John Wu
I had the same issue get value for my property in my service class. I resolved it by using @ConfigurationProperties instead of @Value.
我在我的服务类中遇到了同样的问题,为我的财产获取价值。我通过使用 @ConfigurationProperties 而不是 @Value 解决了它。
- create a class like this:
- 创建一个这样的类:
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "file")
public class FileProperties {
private String directory;
public String getDirectory() {
return directory;
}
public void setDirectory(String dir) {
this.directory = dir;
}
}
- add the following to your BootApplication class:
- 将以下内容添加到您的 BootApplication 类:
@EnableConfigurationProperties({
FileProperties.class
})
- Inject FileProperties to your PrintProperty class, then you can get hold of the property through the getter method.
- 将 FileProperties 注入您的 PrintProperty 类,然后您可以通过 getter 方法获取该属性。