Java 如何在 Spring Boot 中访问 application.properties 文件中定义的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30528255/
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
How to access a value defined in the application.properties file in Spring Boot
提问by Qasim
I want to access values provided in application.properties
, e.g.:
我想访问中提供的值application.properties
,例如:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
I want to access userBucket.path
in my main program in a Spring Boot application.
我想userBucket.path
在 Spring Boot 应用程序中访问我的主程序。
采纳答案by Master Slave
You can use the @Value
annotation and access the property in whichever Spring bean you're using
您可以使用@Value
注释并访问您正在使用的任何 Spring bean 中的属性
@Value("${userBucket.path}")
private String userBucketPath;
The Externalized Configurationsection of the Spring Boot docs, explains all the details that you might need.
Spring Boot 文档的外部化配置部分解释了您可能需要的所有详细信息。
回答by Rodrigo Villalba Zayas
Another way is injecting org.springframework.core.env.Environment
to your bean.
另一种方法是注入org.springframework.core.env.Environment
你的bean。
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
.....
}
回答by JoB?N
@ConfigurationProperties
can be used to map values from .properties
( .yml
also supported) to a POJO.
@ConfigurationProperties
可用于将值从.properties
(.yml
也支持)映射到 POJO。
Consider the following Example file.
考虑以下示例文件。
.properties
。特性
cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket
Employee.java
雇员.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "cust.data.employee")
@Configuration("employeeProperties")
public class Employee {
private String name;
private String dept;
//Getters and Setters go here
}
Now the properties value can be accessed by autowiring employeeProperties
as follows.
现在可以通过自动装配访问属性值employeeProperties
,如下所示。
@Autowired
private Employee employeeProperties;
public void method() {
String employeeName = employeeProperties.getName();
String employeeDept = employeeProperties.getDept();
}
回答by JorgeTovar
You can use the @Value
to load variables from the application.properties
if you will use this value in one place, but if you need a more centralized way to load this variables @ConfigurationProperties
is a better approach.
如果您将在一个地方使用这个值,您可以使用@Value
来加载变量application.properties
,但是如果您需要一种更集中的方式来加载这个变量@ConfigurationProperties
是一种更好的方法。
Additionally you can load variables and cast it automatically if you need different data types to perform your validations and business logic.
此外,如果您需要不同的数据类型来执行验证和业务逻辑,您可以加载变量并自动转换。
application.properties
custom-app.enable-mocks = false
@Value("${custom-app.enable-mocks}")
private boolean enableMocks;
回答by lucifer
You can do it this way as well....
你也可以这样做......
@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {
@Autowired
private Environment env;
public String getConfigValue(String configKey){
return env.getProperty(configKey);
}
}
Then wherever you want to read from application.properties, just pass the key to getConfigValue method.
然后,无论您想从 application.properties 读取的任何内容,只需将键传递给 getConfigValue 方法即可。
@Autowired
ConfigProperties configProp;
// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port");
回答by Ananthapadmanabhan
Spring-boot allows us several methods to provide externalized configurations , you can try using application.yml or yaml files instead of the property file and provide different property files setup according to different environments.
Spring-boot 允许我们提供多种方法来提供外部化配置,您可以尝试使用 application.yml 或 yaml 文件代替属性文件,并根据不同的环境提供不同的属性文件设置。
We can separate out the properties for each environment into separate yml files under separate spring profiles.Then during deployment you can use :
我们可以将每个环境的属性分离到单独的 spring 配置文件下的单独 yml 文件中。然后在部署期间您可以使用:
java -jar -Drun.profiles=SpringProfileName
to specify which spring profile to use.Note that the yml files should be name like
指定要使用的弹簧配置文件。请注意,yml 文件的名称应为
application-{environmentName}.yml
for them to be automatically taken up by springboot.
让它们被 springboot 自动占用。
参考:https: //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties
To read from the application.yml or property file :
从 application.yml 或属性文件中读取:
The easiest wayto read a value from the property file or yml is to use the spring @value annotation.Spring automatically loads all values from the yml to the spring environment , so we can directly use those values from the environment like :
从属性文件或 yml 读取值的最简单方法是使用 spring @value 注释。Spring 自动将 yml 中的所有值加载到 spring 环境中,因此我们可以直接使用环境中的这些值,例如:
@Component
public class MySampleBean {
@Value("${name}")
private String sampleName;
// ...
}
Or another method that spring provides to read strongly typed beans is as follows:
或者 spring 提供的另一种读取强类型 bean 的方法如下:
YML
ymca:
remote-address: 192.168.1.1
security:
username: admin
Corresponding POJO to read the yml :
对应的 POJO 读取 yml :
@ConfigurationProperties("ymca")
public class YmcaProperties {
private InetAddress remoteAddress;
private final Security security = new Security();
public boolean isEnabled() { ... }
public void setEnabled(boolean enabled) { ... }
public InetAddress getRemoteAddress() { ... }
public void setRemoteAddress(InetAddress remoteAddress) { ... }
public Security getSecurity() { ... }
public static class Security {
private String username;
private String password;
public String getUsername() { ... }
public void setUsername(String username) { ... }
public String getPassword() { ... }
public void setPassword(String password) { ... }
}
}
The above method works well with yml files.
上述方法适用于 yml 文件。
Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
参考:https: //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
回答by Rapalagui
For me, none of the above did directly work for me. What I did is the following:
对我来说,以上都没有直接对我有用。我所做的是以下内容:
Additionally to @Rodrigo Villalba Zayas answer up there I addedimplements InitializingBean
to the class
and implemented the method
除了@Rodrigo Villalba Zayas 的回答之外,我还添加implements InitializingBean
了课程
并实现了该方法
@Override
public void afterPropertiesSet() {
String path = env.getProperty("userBucket.path");
}
So that will look like
所以这看起来像
import org.springframework.core.env.Environment;
public class xyz implements InitializingBean {
@Autowired
private Environment env;
private String path;
....
@Override
public void afterPropertiesSet() {
path = env.getProperty("userBucket.path");
}
public void method() {
System.out.println("Path: " + path);
}
}
回答by Naresh Bhadke
Best ways to get property values are using.
获取属性值的最佳方法是使用。
1. Using Value annotation
1. 使用值注解
@Value("${property.key}")
private String propertyKeyVariable;
2. Using Enviornment bean
2. 使用环境bean
@Autowired
private Environment env;
public String getValue() {
return env.getProperty("property.key");
}
public void display(){
System.out.println("# Value : "+getValue);
}
回答by Dhwanil Patel
Currently, I know about the following three ways:
目前,我知道以下三种方式:
1. The @Value
annotation
1.@Value
注释
@Value("${<property.name>}")
private static final <datatype> PROPERTY_NAME;
- In my experience there are some situations when you are not
able to get the value or it is set to
null
. For instance, when you try to set it in apreConstruct()
method or aninit()
method. This happens because the value injection happens after the class is fully constructed. This is why it is better to use the 3'rd option.
- 根据我的经验,在某些情况下,您无法获得该值或将其设置为
null
. 例如,当您尝试在preConstruct()
方法或init()
方法中设置它时。发生这种情况是因为值注入发生在类完全构造之后。这就是为什么最好使用第三个选项的原因。
2. The @PropertySource
annotation
2.@PropertySource
注释
<pre>@PropertySource("classpath:application.properties")
//env is an Environment variable
env.getProperty(configKey);</pre>
PropertySouce
sets values from the property source file in anEnvironment
variable (in your class) when the class is loaded. So you able to fetch easily afterword.- Accessible through System Environment variable.
PropertySouce
Environment
加载类时,将属性源文件中的值设置在变量(在您的类中)中。因此,您可以轻松获取后记。- 可通过系统环境变量访问。
3. The @ConfigurationProperties
annotation.
3.@ConfigurationProperties
注释。
- This is mostly used in Spring projects to load configuration properties.
It initializes an entity based on property data.
@ConfigurationProperties
identifies the property file to load.@Configuration
creates a bean based on configuration file variables.
@ConfigurationProperties(prefix = "user") @Configuration("UserData") class user { //Property & their getter / setter } @Autowired private UserData userData; userData.getPropertyName();
- 这主要用于 Spring 项目中加载配置属性。
它根据属性数据初始化一个实体。
@ConfigurationProperties
标识要加载的属性文件。@Configuration
根据配置文件变量创建一个 bean。
@ConfigurationProperties(prefix = "user") @Configuration("UserData") class user { //Property & their getter / setter } @Autowired private UserData userData; userData.getPropertyName();
回答by MindFlayerA
The best thing is to use @Value
annotation it will automatically assign value to your object private Environment en
.
This will reduce your code and it will be easy to filter your files.
最好的办法是使用@Value
注解,它会自动为你的对象赋值private Environment en
。这将减少您的代码,并且可以轻松过滤您的文件。